import { createRouteHandlerClient } from "@supabase/auth-helpers-nextjs";
import { cookies } from "next/headers";
import { NextRequest, NextResponse } from "next/server";

export const dynamic = "force-dynamic";

export async function GET(
  req: NextRequest,
  { params }: { params: { code: string } }
) {
  try {
    const supabase = createRouteHandlerClient({ cookies });

    const { data: { session } } = await supabase.auth.getSession();
    if (!session) {
      return NextResponse.json({ error: "Non autorisé" }, { status: 401 });
    }

    // Vérifier que l'utilisateur est staff
    const { data: staffUser } = await supabase
      .from("staff_users")
      .select("is_staff")
      .eq("user_id", session.user.id)
      .single();

    if (!staffUser || !staffUser.is_staff) {
      return NextResponse.json({ error: "Accès refusé" }, { status: 403 });
    }

    const referrerCode = params.code;

    // Récupérer les clients apportés par cet apporteur
    const { data: referredClients, error } = await supabase
      .from("organization_details")
      .select(`
        org_id,
        code_employeur,
        organizations!organization_details_org_id_fkey (
          name
        )
      `)
      .eq("is_referred", true)
      .eq("referrer_code", referrerCode)
      .order("organizations(name)");

    if (error) {
      console.error("Erreur lors de la récupération des clients apportés:", error);
      return NextResponse.json({ error: error.message }, { status: 500 });
    }

    return NextResponse.json(referredClients || []);
  } catch (error: any) {
    console.error("Erreur GET /api/staff/referrers/[code]/clients:", error);
    return NextResponse.json(
      { error: error.message || "Erreur serveur" },
      { status: 500 }
    );
  }
}
