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: { orgId: 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 periode = req.nextUrl.searchParams.get("periode") || undefined;

    // Si une période est fournie, on va élargir la recherche sur 2 mois autour
    let startDate: string | undefined;
    let endDate: string | undefined;

    if (periode) {
      const parts = periode.split(" ");
      const monthNames = ["Janvier","Février","Mars","Avril","Mai","Juin","Juillet","Août","Septembre","Octobre","Novembre","Décembre"];
      const periodMonth = monthNames.indexOf(parts[0]) + 1;
      const periodYear = parseInt(parts[1]);
      const month = periodMonth.toString().padStart(2, '0');

      let emissionMonth = periodMonth + 1;
      let emissionYear = periodYear;
      if (emissionMonth > 12) { emissionMonth = 1; emissionYear += 1; }
      const emissionMonthStr = String(emissionMonth).padStart(2, '0');

      startDate = `${periodYear}-${month}-01`;
      endDate = `${emissionYear}-${emissionMonthStr}-20`;
    }

    const orgId = params.orgId;

    let query = supabase
      .from("invoices")
      .select("id, amount_ht, created_at, period_label, org_id")
      .eq("org_id", orgId)
      .order("created_at", { ascending: false })
      .limit(50);

    if (startDate && endDate) {
      query = query.gte("created_at", startDate).lte("created_at", endDate) as any;
    }

    const { data: invoices, error } = await query;

    if (error) {
      console.error("Erreur GET invoices for org:", error);
      return NextResponse.json({ error: error.message }, { status: 500 });
    }

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