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

// 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;
  }
}

/**
 * Récupère les informations client depuis la session utilisateur
 */
async function getClientInfoFromSession(session: any, supabase: any) {
  const userMeta = session?.user?.user_metadata || {};
  const appMeta = session?.user?.app_metadata || {};
  // Vérifier si c'est un utilisateur staff
  // Priorité: valeur côté serveur (table staff_users) car c'est la source de vérité
  let isStaff = false;
  try {
    const { data: staffRow } = await supabase
      .from('staff_users')
      .select('is_staff')
      .eq('user_id', session.user.id)
      .maybeSingle();
    isStaff = !!staffRow?.is_staff;
  } catch (e) {
    // silenced — fallback to session metadata below
  }

  // Fallback: session metadata (in case DB check failed for some reason)
  if (!isStaff) {
    isStaff = Boolean(
      (userMeta.is_staff === true || userMeta.role === 'staff') ||
      (Array.isArray(appMeta.roles) && appMeta.roles.includes('staff'))
    );
  }

  if (isStaff) {
    // For staff users: do not require selecting an active organization.
    // Staff should see all data across organizations, so we return a special
    // marker indicating staff access and no specific org id.
    return {
      id: null,
      name: "Staff Access",
      isStaff: true,
    };
  }

  // Pour un utilisateur normal, récupérer son organisation depuis la DB
  const orgInfo = await getOrganizationFromDatabase(supabase, session.user.id);
  
  if (!orgInfo) {
    throw new Error("User is not associated with any organization");
  }

  return orgInfo;
}

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);
    const debug = url.searchParams.get("debug");
    
    // Récupérer les informations client depuis la DB
    let clientInfo;
    try {
      clientInfo = await getClientInfoFromSession(session, supabase);
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);
      console.error('Failed to get client info:', message);
      return NextResponse.json(
        { error: "forbidden", message },
        { status: 403 }
      );
    }

    // Debug détaillé
    if (debug === "1") {
      return NextResponse.json({
        matricule,
        sessionUserId: session.user.id,
        sessionEmail: session.user.email,
        clientInfo,
        message: "Debug mode - salarie route (Supabase)",
      });
    }

  const organizationId = clientInfo.id; // may be null for staff
  const organizationName = clientInfo.name;

    console.log('🔍 [API /salaries/:matricule] Querying Supabase:', {
      matricule,
      organizationId,
      organizationName,
    });

    // Recherche par code_salarie (prioritaire) ou num_salarie pour robustesse
    let query = supabase
      .from('salaries')
      .select(`
        id, code_salarie, num_salarie, salarie, nom, nom_de_naissance, prenom, civilite, pseudonyme,
        compte_transat, justificatifs_personnels, rf_au_sens_fiscal, intermittent_mineur_16,
        adresse_mail, nir, conges_spectacles, tel, adresse, date_naissance, lieu_de_naissance,
        iban, bic, derniere_profession, employer_id
      `)
      .or(`code_salarie.eq.${matricule},num_salarie.eq.${matricule}`)
      .limit(1);

    // If not staff (organizationId present), scope to the employer
    if (organizationId) {
      query = query.eq('employer_id', organizationId);
    }

    const { data, error } = await query;
    if (error) {
      console.error('💥 [API /salaries/:matricule] Supabase error:', error.message);
      return NextResponse.json({ error: 'supabase_error', detail: error.message }, { status: 500 });
    }
    const r = (data && data[0]) || null;
    if (!r) {
      return NextResponse.json({ error: 'not_found' }, { status: 404 });
    }

    const transat = String(r.compte_transat || '').toLowerCase();
    const salarie = {
      matricule: r.code_salarie || r.num_salarie || r.id,
      civilite: r.civilite || undefined,
      prenom: r.prenom || undefined,
      nom_usage: r.nom || r.salarie || undefined,
      pseudo: r.pseudonyme || undefined,
      nom_naissance: r.nom_de_naissance || undefined,
      date_naissance: r.date_naissance || undefined, // 'YYYY-MM-DD'
      lieu_naissance: r.lieu_de_naissance || undefined,
      email: r.adresse_mail || undefined,
      telephone: r.tel || undefined,
      adresse: r.adresse || undefined,
      nir: r.nir || undefined,
      conges_spectacles: r.conges_spectacles || undefined,
      iban: r.iban || undefined,
      bic: r.bic || undefined,
      transat_connecte: transat.includes('connect') && !transat.includes('non'),
      justificatifs: r.justificatifs_personnels || undefined,
      mineur_moins_16: typeof r.intermittent_mineur_16 === 'boolean' ? r.intermittent_mineur_16 : undefined,
      resident_fr: typeof r.rf_au_sens_fiscal === 'boolean' ? r.rf_au_sens_fiscal : undefined,
      rib_pdf: null,
    };

    console.log('✅ [API /salaries/:matricule] Found:', { matricule: salarie.matricule, nom: salarie.nom_usage });
    return NextResponse.json(salarie);

  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.error("💥 ERROR in salarie route (UPSTREAM):", message);

    if (message.includes('not_found')) {
      return NextResponse.json({ error: 'not_found' }, { status: 404 });
    }

    return NextResponse.json(
      {
        error: "internal_server_error",
        message: "Une erreur est survenue lors de la récupération du salarié"
      },
      { status: 500 }
    );
  }
}
