import type { JwtPayload } from '../middleware/auth.js';
import { sql } from '../db.js';

/** Staff (admin / agent) sees all tickets; company users only tickets tied to their company via contact.company_id */
export async function userCanAccessTicket(user: JwtPayload, ticketId: string): Promise<boolean> {
  if (user.role === 'admin' || user.role === 'user') return true;
  const cid = user.company_id ?? null;
  if (user.role !== 'company_user' || !cid) return false;

  const [row] = await sql<[{ ok: boolean }]>`
    SELECT EXISTS (
      SELECT 1 FROM tickets t
      INNER JOIN contacts c ON c.id = t.contact_id
      WHERE t.id = ${ticketId} AND c.company_id = ${cid}
    ) AS ok
  `;
  return Boolean(row?.ok);
}
