// app/api/staff/facturation/[id]/pdf-url/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;
  }
}

// GET - Retourner l'URL pour visualiser le PDF de la facture
export async function GET(req: Request, { params }: { params: { id: string } }) {
  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 isStaff = await isStaffUser(supabase, session.user.id);
    if (!isStaff) {
      return NextResponse.json({ error: 'forbidden', message: 'Staff access required' }, { status: 403 });
    }

    // Récupérer la facture pour vérifier qu'elle a un PDF
    const { data: invoice, error: invoiceError } = await supabase
      .from('invoices')
      .select('pdf_s3_key, invoice_number')
      .eq('id', params.id)
      .single();

    if (invoiceError || !invoice || !invoice.pdf_s3_key) {
      return NextResponse.json({ error: 'PDF non trouvé pour cette facture' }, { status: 404 });
    }

    // Retourner l'URL du endpoint view-pdf
    const pdfUrl = `/api/staff/facturation/${params.id}/view-pdf`;

    return NextResponse.json({ pdfUrl });
  } catch (error) {
    console.error('[pdf-url] Error:', error);
    const message = error instanceof Error ? error.message : String(error);
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
