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

export const dynamic = "force-dynamic";

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

export default async function StaffAvenantsPage() {
  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>
    );
  }

  // Récupérer les avenants depuis la base de données
  // Ordre par défaut: date d'effet décroissant (plus récent d'abord)
  const { data: avenants, error } = await sb
    .from("avenants")
    .select(`
      id,
      numero_avenant,
      date_avenant,
      date_effet,
      type_avenant,
      motif_avenant,
      elements_avenantes,
      statut,
      contract_id,
      created_at,
      signature_status,
      last_employer_notification_at,
      last_employee_notification_at,
      cddu_contracts!inner(
        contract_number,
        employee_name,
        employee_matricule,
        structure,
        org_id,
        production_name
      )
    `)
    .order("date_effet", { ascending: false })
    .order("created_at", { ascending: false });

  if (error) {
    console.error("Erreur récupération avenants:", error);
  }

  // Transformer les données pour le format attendu
  const formattedAvenants = (avenants || []).map((a: any) => ({
    id: a.id,
    numero_avenant: a.numero_avenant,
    contract_id: a.contract_id,
    contract_number: a.cddu_contracts?.contract_number,
    employee_name: a.cddu_contracts?.employee_name,
    employee_matricule: a.cddu_contracts?.employee_matricule,
    organization_name: a.cddu_contracts?.structure,
    production_name: a.cddu_contracts?.production_name,
    date_effet: a.date_effet,
    date_avenant: a.date_avenant,
    type_avenant: a.type_avenant,
    motif_avenant: a.motif_avenant,
    status: a.statut,
    elements: a.elements_avenantes || [],
    created_at: a.created_at,
    signature_status: a.signature_status,
    last_employer_notification_at: a.last_employer_notification_at,
    last_employee_notification_at: a.last_employee_notification_at,
  }));

  return (
    <main className="p-6">
      <StaffAvenantsPageClient initialData={formattedAvenants} />
    </main>
  );
}
