// app/(app)/staff/contrats/page.tsx
import { cookies } from "next/headers";
import NextDynamic from "next/dynamic";
import { createSbServer } from "@/lib/supabaseServer";

export const dynamic = "force-dynamic";

const StaffContractsPageClient = NextDynamic<any>(() => import("../../../../components/staff/StaffContractsPageClient"), { ssr: false });

export default async function StaffContractsPage() {
  const sb = createSbServer();
  const { data: { user } } = await sb.auth.getUser();

  if (!user) {
    return (
      <main className="p-6">
        <h1 className="text-lg font-semibold">Accès refusé</h1>
        <p className="text-sm text-slate-600">Vous devez être connecté.</p>
      </main>
    );
  }

  const { data: me } = await sb.from("staff_users").select("is_staff").eq("user_id", user.id).maybeSingle();
  const isStaff = !!me?.is_staff;
  if (!isStaff) {
    return (
      <main className="p-6">
        <h1 className="text-lg font-semibold">Accès refusé</h1>
        <p className="text-sm text-slate-600">Cette page est réservée au Staff.</p>
      </main>
    );
  }

  // initial fetch: server-side list of latest contracts (sans limite)
  // Utiliser une jointure pour récupérer le nom depuis la table salaries
  // Par défaut, afficher tous les contrats (terminés et non terminés) - l'utilisateur peut filtrer ensuite
  const { data: contracts, error } = await sb
    .from("cddu_contracts")
    .select(
      `id, contract_number, employee_name, employee_id, structure, type_de_contrat, profession, production_name, start_date, end_date, created_at, etat_de_la_demande, etat_de_la_paie, dpae, gross_pay, org_id, contrat_signe_par_employeur, contrat_signe, last_employer_notification_at, last_employee_notification_at, analytique, nombre_d_heures, n_objet, objet_spectacle, type_salaire,
      salaries!employee_id(salarie, nom, prenom, adresse_mail, code_salarie),
      organizations!org_id(organization_details(code_employeur))`
    )
    .order("start_date", { ascending: false });

  // Server-side debug logging to help diagnose empty results (will appear in Next.js server logs)
  try {
    console.log("[staff/contrats] supabase fetch cddu_contracts result count:", Array.isArray(contracts) ? contracts.length : typeof contracts);
    if (error) console.log("[staff/contrats] supabase error:", error);
    if (contracts && contracts.length > 0) console.log("[staff/contrats] sample:", contracts.slice(0, 5));
  } catch (e) {
    // ignore logging errors
  }

  if (error) {
    return (
      <main className="p-6">
        <h1 className="text-lg font-semibold">Erreur</h1>
        <p className="text-sm text-rose-600">{error.message}</p>
        <div className="mt-4 p-3 bg-slate-50 rounded text-sm text-slate-700">
          <div><strong>Debug</strong></div>
          <div>Supabase returned an error when reading <code>cddu_contracts</code>. See server logs for details.</div>
        </div>
      </main>
    );
  }

  // active org (optional) for staff we allow global view; keep cookie reading for parity
  const c = cookies();
  const activeOrgId = c.get("active_org_id")?.value || null;

  return (
    <main className="p-6">
      {(!contracts || contracts.length === 0) && (
        <div className="mb-4 p-3 rounded bg-yellow-50 text-sm text-slate-800 border">
          <div><strong>Debug:</strong> Aucun contrat trouvé côté serveur (initialData vide).</div>
          <div className="mt-2 text-xs text-slate-600">Si tu utilises Realtime / RLS, vérifie que la table <code>cddu_contracts</code> est publiée pour Realtime et que les policies autorisent la lecture pour ton utilisateur staff.</div>
          <details className="mt-2 text-xs">
            <summary className="cursor-pointer text-xs underline">Voir le payload serveur (preview)</summary>
            <pre className="mt-2 max-h-48 overflow-auto text-xs bg-slate-50 p-2 rounded border">{JSON.stringify(contracts ?? [], null, 2)}</pre>
          </details>
        </div>
      )}
      <StaffContractsPageClient initialData={contracts ?? []} activeOrgId={activeOrgId} />
    </main>
  );
}
