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

import { NextResponse } from "next/server";
import { createSbServer } from "@/lib/supabaseServer";

/**
 * Récupère les emails de signature (employeur) pour plusieurs organisations
 * POST /api/staff/organizations/emails
 * Body: { org_ids: string[] }
 */
export async function POST(req: Request) {
  try {
    const sb = createSbServer();
    
    // Vérification de l'authentification
    const { data: { user } } = await sb.auth.getUser();
    if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

    // Vérification des droits staff
    const { data: me } = await sb.from("staff_users").select("is_staff").eq("user_id", user.id).maybeSingle();
    if (!me?.is_staff) return NextResponse.json({ error: "Forbidden" }, { status: 403 });

    const body = await req.json();
    const orgIds = body.org_ids as string[];

    if (!Array.isArray(orgIds) || orgIds.length === 0) {
      return NextResponse.json({ error: "org_ids array required" }, { status: 400 });
    }

    // Récupérer les emails de signature pour toutes les organisations
    const { data, error } = await sb
      .from("organization_details")
      .select("org_id, email_signature")
      .in("org_id", orgIds);

    if (error) {
      console.error('Error fetching organization emails:', error);
      return NextResponse.json({ error: error.message }, { status: 500 });
    }

    return NextResponse.json(data || []);
  } catch (err: any) {
    console.error('Unexpected error in /api/staff/organizations/emails:', err);
    return NextResponse.json({ error: err.message || "Internal Server Error" }, { status: 500 });
  }
}
