// app/api/staff/facturation/bulk-update-invoice-date/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;
  }
}

// POST - Mise à jour en masse des dates de facture
export async function POST(req: Request) {
  try {
    const body = await req.json();
    const { invoiceIds, invoiceDate } = body;

    // Validation des données
    if (!Array.isArray(invoiceIds) || invoiceIds.length === 0) {
      return NextResponse.json({ error: 'invalid_invoice_ids' }, { status: 400 });
    }

    if (!invoiceDate || typeof invoiceDate !== 'string') {
      return NextResponse.json({ error: 'invalid_invoice_date' }, { status: 400 });
    }

    // Validation du format de date
    const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
    if (!dateRegex.test(invoiceDate)) {
      return NextResponse.json({ error: 'invalid_date_format' }, { status: 400 });
    }

    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 });
    }

    // Limiter le nombre d'IDs pour éviter les abus
    if (invoiceIds.length > 100) {
      return NextResponse.json({ error: 'too_many_invoices', message: 'Maximum 100 invoices per batch' }, { status: 400 });
    }

    // Vérifier que toutes les factures existent et appartiennent à des organisations valides
    const { data: existingInvoices, error: checkError } = await supabase
      .from('invoices')
      .select('id, invoice_number, org_id')
      .in('id', invoiceIds);

    if (checkError) {
      console.error('[api/staff/facturation/bulk-update-invoice-date] Check error:', checkError);
      return NextResponse.json({ error: 'database_error', detail: checkError.message }, { status: 500 });
    }

    if (!existingInvoices || existingInvoices.length !== invoiceIds.length) {
      return NextResponse.json({ error: 'some_invoices_not_found' }, { status: 404 });
    }

    // Effectuer la mise à jour en masse
    const { data: updatedInvoices, error: updateError } = await supabase
      .from('invoices')
      .update({ 
        invoice_date: invoiceDate,
        updated_at: new Date().toISOString()
      })
      .in('id', invoiceIds)
      .select('id, invoice_number, invoice_date');

    if (updateError) {
      console.error('[api/staff/facturation/bulk-update-invoice-date] Update error:', updateError);
      return NextResponse.json({ error: 'update_failed', detail: updateError.message }, { status: 500 });
    }

    console.log(`[api/staff/facturation/bulk-update-invoice-date] Updated ${updatedInvoices?.length || 0} invoices with invoice date ${invoiceDate}`);

    return NextResponse.json({
      success: true,
      updated_count: updatedInvoices?.length || 0,
      invoice_date: invoiceDate,
      message: `${updatedInvoices?.length || 0} facture(s) mise(s) à jour avec succès`
    });

  } catch (error) {
    console.error('[api/staff/facturation/bulk-update-invoice-date] Unexpected error:', error);
    const message = error instanceof Error ? error.message : String(error);
    return NextResponse.json({ error: 'internal_server_error', message }, { status: 500 });
  }
}