// app/api/staff/cotisations/notifications/route.ts
import { NextResponse, NextRequest } 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";

/**
 * GET /api/staff/cotisations/notifications
 * Récupère toutes les notifications de cotisations envoyées
 * Query params:
 *  - org_id: filtrer par organisation
 *  - year: filtrer par année
 */
export async function GET(req: NextRequest) {
  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 { data: staffRow } = await supabase
      .from("staff_users")
      .select("is_staff")
      .eq("user_id", session.user.id)
      .maybeSingle();
    
    const isStaff = !!staffRow?.is_staff;
    
    if (!isStaff) {
      return NextResponse.json(
        { error: "forbidden", message: "Staff access required" },
        { status: 403 }
      );
    }

    // Récupérer les paramètres de requête
    const { searchParams } = new URL(req.url);
    const orgId = searchParams.get("org_id");
    const year = searchParams.get("year");

    // Construire la requête
    let query = supabase
      .from("contribution_notifications")
      .select("*")
      .order("notified_at", { ascending: false });

    if (orgId) {
      query = query.eq("org_id", orgId);
    }

    if (year) {
      // Filtrer par année dans period_label (ex: "Août 2025")
      query = query.like("period_label", `%${year}%`);
    }

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

    if (error) {
      console.error("[notifications] Error fetching notifications:", error);
      return NextResponse.json(
        { error: "failed_to_fetch", message: error.message },
        { status: 500 }
      );
    }

    return NextResponse.json({ notifications: notifications || [] });

  } catch (error: any) {
    console.error("[notifications] Unexpected error:", error);
    return NextResponse.json(
      { error: "internal_error", message: error?.message || "Unknown error" },
      { status: 500 }
    );
  }
}
