// app/api/staff/contrats/[id]/route.ts
import { createSbServer } from "@/lib/supabaseServer";
import { NextRequest, NextResponse } from "next/server";

export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const sb = createSbServer();
    
    // Vérifier l'authentification
    const { data: { user } } = await sb.auth.getUser();
    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    // Vérifier que c'est un staff
    const { data: me } = await sb
      .from("staff_users")
      .select("is_staff")
      .eq("user_id", user.id)
      .maybeSingle();

    if (!me?.is_staff) {
      return NextResponse.json({ error: "Forbidden" }, { status: 403 });
    }

    const contractId = params.id;

    // Récupérer les détails du contrat avec la jointure salaries
    // Utiliser le même format que dans app/(app)/staff/contrats/[id]/page.tsx
    const { data: contract, error } = await sb
      .from("cddu_contracts")
      .select("*, salaries!employee_id(salarie, nom, prenom, adresse_mail, code_salarie)")
      .eq("id", contractId)
      .single();

    if (error) {
      console.error("[GET /api/staff/contrats/[id]] Database error:", error);
      console.error("[GET /api/staff/contrats/[id]] Error details:", error.message, error.code);
      return NextResponse.json({ error: "Database error", details: error.message }, { status: 500 });
    }

    if (!contract) {
      return NextResponse.json({ error: "Contract not found" }, { status: 404 });
    }

    return NextResponse.json(contract);
  } catch (error) {
    console.error("[GET /api/staff/contrats/[id]] Error:", error);
    return NextResponse.json({ error: "Internal server error" }, { status: 500 });
  }
}
