// app/api/public/invoices/[id]/download/route.ts
import { NextResponse } from "next/server";
import { createClient } from "@supabase/supabase-js";
import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";

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

/**
 * Route publique pour télécharger une facture
 * Génère un lien pré-signé S3 à la volée et redirige vers le PDF
 * 
 * Usage: GET /api/public/invoices/[id]/download?token=[optional_token]
 */
export async function GET(
  req: Request, 
  { params }: { params: { id: string } }
) {
  try {
    console.log('[api/public/invoices/download] Request for invoice:', params.id);

    // Créer un client Supabase avec la service role key pour accès direct
    const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
    const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY;

    if (!supabaseUrl || !supabaseServiceKey) {
      console.error('[api/public/invoices/download] Missing Supabase configuration');
      return NextResponse.json(
        { error: 'Configuration error' }, 
        { status: 500 }
      );
    }

    const supabase = createClient(supabaseUrl, supabaseServiceKey);

    // Récupérer la facture
    const { data: invoice, error: invoiceError } = await supabase
      .from('invoices')
      .select('id, pdf_s3_key, invoice_type, invoice_number, status')
      .eq('id', params.id)
      .single();

    if (invoiceError || !invoice) {
      console.error('[api/public/invoices/download] Invoice not found:', invoiceError);
      return NextResponse.json(
        { error: 'Facture introuvable' }, 
        { status: 404 }
      );
    }

    // Vérifier que la facture a bien un PDF
    if (!invoice.pdf_s3_key) {
      console.error('[api/public/invoices/download] No PDF for invoice:', params.id);
      return NextResponse.json(
        { error: 'PDF non disponible pour cette facture' }, 
        { status: 404 }
      );
    }

    // Vérifier que c'est bien une facture studio (sécurité)
    if (invoice.invoice_type !== 'studio_renouvellement' && invoice.invoice_type !== 'studio_site_web') {
      console.warn('[api/public/invoices/download] Attempt to access non-studio invoice:', {
        invoiceId: params.id,
        type: invoice.invoice_type
      });
      // On pourrait bloquer ici, mais pour l'instant on laisse passer
      // return NextResponse.json({ error: 'Accès non autorisé' }, { status: 403 });
    }

    // Générer le lien pré-signé S3
    const bucket = (process.env.AWS_S3_BUCKET || 'odentas-docs').trim();
    const region = process.env.AWS_REGION || 'eu-west-3';
    const expireSeconds = 900; // 15 minutes - suffisant pour un téléchargement

    const s3Client = new S3Client({ region });
    const command = new GetObjectCommand({ 
      Bucket: bucket, 
      Key: invoice.pdf_s3_key 
    });

    const signedUrl = await getSignedUrl(s3Client, command, { 
      expiresIn: expireSeconds 
    });

    console.log('[api/public/invoices/download] Generated presigned URL for invoice:', {
      invoiceId: params.id,
      invoiceNumber: invoice.invoice_number,
      type: invoice.invoice_type,
      expiresIn: `${expireSeconds}s`
    });

    // Rediriger vers le PDF
    return NextResponse.redirect(signedUrl, 307); // 307 = Temporary Redirect

  } catch (error) {
    console.error('[api/public/invoices/download] Error:', error);
    const message = error instanceof Error ? error.message : String(error);
    return NextResponse.json(
      { error: 'Erreur lors de la génération du lien de téléchargement', message }, 
      { status: 500 }
    );
  }
}
