// app/api/staff/payslips/missing-organizations/route.ts
import { createSbServer } from "@/lib/supabaseServer";
import { NextRequest, NextResponse } from "next/server";

export async function GET(request: NextRequest) {
  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 searchParams = request.nextUrl.searchParams;
    const periodFrom = searchParams.get("period_from");
    const periodTo = searchParams.get("period_to");

    if (!periodFrom || !periodTo) {
      return NextResponse.json({ 
        organizations: [],
        message: "Filtres incomplets" 
      });
    }

    console.log("[GET /api/staff/payslips/missing-organizations] Params:", {
      periodFrom,
      periodTo
    });

    // Récupérer tous les contrats dans cette période
    const { data: contracts, error: contractsError } = await sb
      .from("cddu_contracts")
      .select(`
        id, 
        start_date, 
        end_date, 
        type_de_contrat,
        structure,
        org_id,
        etat_de_la_demande
      `)
      .lte("start_date", periodTo)
      .gte("end_date", periodFrom)
      .neq("etat_de_la_demande", "Annulée");

    if (contractsError) {
      console.error("[GET /api/staff/payslips/missing-organizations] Contracts error:", contractsError);
      return NextResponse.json({ error: "Database error" }, { status: 500 });
    }

    if (!contracts || contracts.length === 0) {
      return NextResponse.json({ 
        organizations: [],
        total_contracts: 0
      });
    }

    console.log("[GET /api/staff/payslips/missing-organizations] Found contracts:", contracts.length);

    // Récupérer les informations des organisations uniques
    const uniqueOrgIds = [...new Set(contracts.map(c => c.org_id).filter(Boolean))];
    const { data: organizationsData, error: orgsError } = await sb
      .from("organizations")
      .select("id, name, structure_api")
      .in("id", uniqueOrgIds);

    if (orgsError) {
      console.error("[GET /api/staff/payslips/missing-organizations] Organizations error:", orgsError);
    }

    // Créer un map pour accéder rapidement aux noms des organisations
    const orgNamesMap = new Map<string, string>();
    if (organizationsData) {
      organizationsData.forEach(org => {
        const orgName = org.name || org.structure_api || `Organisation ${org.id}`;
        orgNamesMap.set(org.id, orgName);
      });
    }

    // Récupérer toutes les paies pour ces contrats
    const contractIds = contracts.map(c => c.id);
    const { data: payslips, error: payslipsError } = await sb
      .from("payslips")
      .select("contract_id, period_month")
      .in("contract_id", contractIds);

    if (payslipsError) {
      console.error("[GET /api/staff/payslips/missing-organizations] Payslips error:", payslipsError);
      return NextResponse.json({ error: "Database error" }, { status: 500 });
    }

    console.log("[GET /api/staff/payslips/missing-organizations] Found payslips:", payslips?.length || 0);

    // Créer un map des contrats avec paies
    const contractsWithPayslips = new Set<string>();
    if (payslips) {
      payslips.forEach(p => contractsWithPayslips.add(p.contract_id));
    }

    // Grouper par organisation et compter les contrats sans paie
    const orgMap = new Map<string, { name: string; missingCount: number }>();

    contracts.forEach(contract => {
      const startDate = new Date(contract.start_date);
      const endDate = new Date(contract.end_date);
      const isMultiMonth = startDate.getMonth() !== endDate.getMonth() || 
                           startDate.getFullYear() !== endDate.getFullYear();
      
      let isMissing = false;

      if (!isMultiMonth) {
        // Mono-mois : pas de paie du tout
        isMissing = !contractsWithPayslips.has(contract.id);
      } else {
        // Multi-mois ou RG : vérifier s'il y a une paie dans la période demandée
        const contractPayslips = payslips?.filter(p => p.contract_id === contract.id) || [];
        
        // Vérifier si au moins une paie couvre la période
        const hasPeriodPayslip = contractPayslips.some(p => {
          const payslipMonth = new Date(p.period_month);
          const requestedFrom = new Date(periodFrom);
          const requestedTo = new Date(periodTo);
          
          // Vérifier si le mois de paie est dans la période demandée
          return payslipMonth >= requestedFrom && payslipMonth <= requestedTo;
        });
        
        isMissing = !hasPeriodPayslip;
      }

      if (isMissing && contract.org_id) {
        const orgId = contract.org_id;
        const orgName = orgNamesMap.get(orgId) || 
                        contract.structure || 
                        `Organisation ${orgId}`;
        
        const existing = orgMap.get(orgId);
        if (existing) {
          existing.missingCount++;
        } else {
          orgMap.set(orgId, {
            name: orgName,
            missingCount: 1
          });
        }
      }
    });

    // Convertir en tableau et trier par ordre alphabétique du nom
    const organizationsList = Array.from(orgMap.entries())
      .map(([id, data]) => ({
        organization_id: id,
        organization_name: data.name,
        missing_count: data.missingCount
      }))
      .sort((a, b) => a.organization_name.localeCompare(b.organization_name, 'fr'));

    // Calculer le nombre total de contrats sans paie
    const totalMissingContracts = organizationsList.reduce((sum, org) => sum + org.missing_count, 0);

    console.log("[GET /api/staff/payslips/missing-organizations] Organizations:", organizationsList.length);

    return NextResponse.json({ 
      organizations: organizationsList,
      total_organizations: organizationsList.length,
      total_missing_contracts: totalMissingContracts
    });
  } catch (error) {
    console.error("[GET /api/staff/payslips/missing-organizations] Error:", error);
    return NextResponse.json({ error: "Internal server error" }, { status: 500 });
  }
}
