// app/api/salaries/[matricule]/contrats/route.ts
import { NextResponse } from "next/server";
import { createRouteHandlerClient } from "@supabase/auth-helpers-nextjs";
import { cookies } from "next/headers";
import { fetchUpstream } from "@/lib/upstream";
import { resolveActiveOrg } from '@/lib/resolveActiveOrg';

// Force dynamic rendering and disable revalidation cache for this proxy
export const dynamic = 'force-dynamic';
export const revalidate = 0;
export const runtime = 'nodejs';

/**
 * Récupère les informations de l'organisation depuis la base de données
 */
async function getOrganizationFromDatabase(supabase: any, userId: string) {
  try {
    // 1. Récupérer l'organisation de l'utilisateur via organization_members
    const { data: memberData, error: memberError } = await supabase
      .from('organization_members')
      .select('org_id')
      .eq('user_id', userId)
      .single();

    if (memberError || !memberData?.org_id) {
      console.log('User not found in organization_members:', { userId, error: memberError });
      return null;
    }

    // 2. Récupérer le nom de l'organisation via organizations.structure_api
    const { data: orgData, error: orgError } = await supabase
      .from('organizations')
      .select('structure_api')
      .eq('id', memberData.org_id)
      .single();

    if (orgError || !orgData?.structure_api) {
      console.log('Organization not found:', { orgId: memberData.org_id, error: orgError });
      return null;
    }

    return {
      id: memberData.org_id,
      name: orgData.structure_api,
      isStaff: false
    };

  } catch (error) {
    console.error('Error fetching organization:', error);
    return null;
  }
}

// We'll use the centralized resolver `resolveActiveOrg` below. It normalizes cookie/header
// values and returns `null` for staff (meaning global access). For non-staff users it
// will return their organization id or null if none found.

export async function GET(
  req: Request,
  { params }: { params: { matricule: string } }
) {
  try {
    // Créer le client Supabase pour vérifier l'authentification
    const supabase = createRouteHandlerClient({ cookies });
    const { data: { session } } = await supabase.auth.getSession();

    if (!session) {
      return NextResponse.json(
        { error: "unauthorized", message: "Vous devez être connecté pour accéder à cette ressource" },
        { status: 401 }
      );
    }

    const matricule = params.matricule;
    const url = new URL(req.url);
    
    // Resolve active organization using central helper. This will normalize cookie/header
    // values and return null for staff (meaning global access to all Supabase rows).
    const sb = createRouteHandlerClient({ cookies });
    const orgId = await resolveActiveOrg(sb as any);

    console.log('🔍 SALARIE CONTRATS ACCESS:', {
      matricule,
      queryParams: Object.fromEntries(url.searchParams.entries()),
      userId: session.user.id,
      orgId
    });

    // Instead of proxying to Airtable/upstream, read contracts from Supabase (cddu_contracts)
  // sb already created above

    // Pagination
    const page = parseInt(url.searchParams.get('page') || '1', 10) || 1;
    const limit = parseInt(url.searchParams.get('limit') || '20', 10) || 20;
    const offset = (page - 1) * limit;

    // Year / period filters (frontend sends year)
    const yearParam = url.searchParams.get('year');
    const year = yearParam ? parseInt(yearParam, 10) : undefined;

    // Build base query against cddu_contracts for this org (if orgId present)
    let query: any = sb.from('cddu_contracts').select('*');
    if (orgId) {
      query = query.eq('org_id', orgId);
    }

    // Try to match matricule against possible columns
    // Common columns: code_salarie, num_salarie, employee_code, employee_number
    // We use or(...) to try multiple equality checks
    const esc = (v: string) => v.replace(/'/g, "''");
    const m = String(matricule || '').trim();
    if (m) {
      // Use only columns that exist on cddu_contracts: employee_matricule (exact),
      // and fuzzy matches on contract_number or employee_name.
      const like = `%${m}%`;
      const orExpr = `employee_matricule.eq.${m},contract_number.ilike.%${m}%,employee_name.ilike.%${m}%`;
      query = query.or(orExpr);
    }

    // Order by created_at desc to have recent first
    query = query.order('created_at', { ascending: false });

    const { data, error } = await query;
    if (error) {
      console.error('💥 Supabase error fetching cddu_contracts for salarie:', error.message);
      return NextResponse.json({ error: error.message }, { status: 500 });
    }

    // Filter by year if provided: check start_date or end_date
    const filtered = (data || []).filter((row: any) => {
      if (!year) return true;
      const d = row.start_date || row.end_date || row.date_debut || row.date_fin;
      if (!d) return false;
      const dt = new Date(d);
      if (isNaN(dt.getTime())) return false;
      return dt.getFullYear() === year;
    });


    // Sort by most recent contract date (prefer end_date/date_fin, fallback to start_date/date_debut)
    filtered.sort((a: any, b: any) => {
      const aEnd = a.end_date || a.date_fin || a.finish_date || null;
      const bEnd = b.end_date || b.date_fin || b.finish_date || null;
      const aStart = a.start_date || a.date_debut || null;
      const bStart = b.start_date || b.date_debut || null;

      const aKey = aEnd ? new Date(aEnd).getTime() : (aStart ? new Date(aStart).getTime() : 0);
      const bKey = bEnd ? new Date(bEnd).getTime() : (bStart ? new Date(bStart).getTime() : 0);
      return bKey - aKey; // descending: newest first
    });

    // Pagination in-memory after sorting
    const paged = filtered.slice(offset, offset + limit);

    const items = paged.map((row: any) => {
      const isMulti = row.multi_mois === 'Oui' || row.multi_mois === true || row.is_multi_mois === true;
      const td = String(row.type_d_embauche || '').toLowerCase();
      const isRG = td.includes('régime général') || td.includes('regime general') || td === 'rg';
      return {
        id: row.id,
        reference: row.contract_number || row.reference || row.contract_ref || row.reference_contract || '',
        profession: row.profession || row.role || '',
        date_debut: row.start_date || row.date_debut || null,
        date_fin: row.end_date || row.date_fin || null,
        is_multi_mois: isMulti,
        regime: isRG ? 'RG' : (isMulti ? 'CDDU_MULTI' : 'CDDU_MONO'),
      };
    });

    console.log('✅ SALARIE CONTRATS (Supabase):', { matricule, userId: session.user.id, orgId, count: items.length });

    return NextResponse.json({ items, page, limit, hasMore: filtered.length > offset + limit });

  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.error("💥 ERROR in salarie contrats route:", message);
    return NextResponse.json(
      {
        error: "internal_server_error",
        message: "Une erreur est survenue lors de la récupération des contrats",
        detail: message,
      },
      { status: 500 }
    );
  }
}