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

export const dynamic = 'force-dynamic';
export const revalidate = 0;
export const runtime = 'nodejs';

async function isStaffUser(supabase: any, userId: string): Promise<boolean> {
  try {
    const { data: staffRow } = await supabase
      .from('staff_users')
      .select('is_staff')
      .eq('user_id', userId)
      .maybeSingle();
    return !!staffRow?.is_staff;
  } catch {
    return false;
  }
}

// GET - Lister toutes les organisations (staff uniquement)
export async function GET(req: Request) {
  try {
    const supabase = createRouteHandlerClient({ cookies });
    const { data: { session } } = await supabase.auth.getSession();
    if (!session) return NextResponse.json({ error: 'unauthorized' }, { status: 401 });

    // Vérifier que l'utilisateur est staff
    const isStaff = await isStaffUser(supabase, session.user.id);
    if (!isStaff) {
      return NextResponse.json({ error: 'forbidden', message: 'Staff access required' }, { status: 403 });
    }

    // Récupérer toutes les organisations avec leurs détails
    const { data: organizations, error } = await supabase
      .from('organizations')
      .select(`
        id, 
        name, 
        structure_api,
        organization_details!inner(code_employeur)
      `)
      .order('name');

    if (error) {
      console.error('[api/staff/organizations] error:', error.message);
      return NextResponse.json({ error: 'supabase_error', detail: error.message }, { status: 500 });
    }

    // Formater les données pour inclure code_employeur au premier niveau
    const formattedOrgs = organizations?.map((org: any) => ({
      id: org.id,
      name: org.name,
      structure_api: org.structure_api,
      code_employeur: org.organization_details?.code_employeur || null,
    })) || [];

    return NextResponse.json({ organizations: formattedOrgs });
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    return NextResponse.json({ error: 'internal_server_error', message }, { status: 500 });
  }
}