import "server-only";
import { query } from "../connection";

export type TechnicienRow = {
  id: number;
  tenant_id: number | null;
  tenant_slug: string | null;
  tenant_name: string | null;
  nom: string;
  prenom: string;
  email: string | null;
  telephone: string | null;
  role: string | null;
  actif: number;
  is_superadmin: number;
  date_embauche: Date | null;
  created_at: Date;
};

// Cross-tenant : on inclut les super-admins (tenant_id IS NULL) et tous les
// techniciens de tous les tenants. La jointure left-join sur tenants gère
// les super-admins (qui n'ont pas de tenant_id et donc pas de tenant_*).
export async function listTechniciens(): Promise<TechnicienRow[]> {
  return query<TechnicienRow>(`
    SELECT
      t.id, t.tenant_id, t.nom, t.prenom, t.email, t.telephone, t.role,
      t.actif, t.is_superadmin, t.date_embauche, t.created_at,
      tn.slug AS tenant_slug,
      tn.name AS tenant_name
    FROM techniciens t
    LEFT JOIN tenants tn ON tn.id = t.tenant_id
    ORDER BY t.is_superadmin DESC, tn.name ASC, t.nom ASC, t.prenom ASC
  `);
}
