import { createSbServer } from "@/lib/supabaseServer";
import { redirect, notFound } from "next/navigation";
import AvenantDetailPageClient from "@/components/staff/avenants/AvenantDetailPageClient";

export const dynamic = "force-dynamic";

export default async function AvenantDetailPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;
  const sb = createSbServer();
  const { data: { user } } = await sb.auth.getUser();

  if (!user) {
    redirect("/login");
  }

  const { data: me } = await sb
    .from("staff_users")
    .select("is_staff")
    .eq("user_id", user.id)
    .maybeSingle();

  const isStaff = !!me?.is_staff;
  if (!isStaff) {
    redirect("/dashboard");
  }

  // Récupérer l'avenant avec les informations du contrat
  const { data: avenant, error } = await sb
    .from("avenants")
    .select(`
      *,
      cddu_contracts (
        *,
        organizations (
          id,
          name,
          organization_details (
            email_signature
          )
        ),
        salaries (
          prenom,
          nom,
          adresse_mail
        )
      )
    `)
    .eq("id", id)
    .single();

  console.log("Recherche avenant ID:", id);
  console.log("Résultat:", { avenant, error });

  if (error || !avenant) {
    console.error("Erreur ou avenant non trouvé:", error);
    notFound();
  }

  return (
    <main className="p-6">
      <AvenantDetailPageClient avenant={avenant} />
    </main>
  );
}
