import { NextRequest } from 'next/server';
import { prisma } from '@/lib/prisma';
import fs from 'fs/promises';
import path from 'path';

export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const resolvedParams = await params;
  const id = resolvedParams.id;
  if (!id) {
    return new Response(JSON.stringify({ error: 'ID facture invalide' }), {
      status: 400,
      headers: { 'Content-Type': 'application/json' },
    });
  }
  try {
    const facture = await prisma.facture.findUnique({ where: { id } });
    if (!facture || !facture.pdfPath) {
      return new Response(JSON.stringify({ error: 'Facture ou fichier non trouvé' }), {
        status: 404,
        headers: { 'Content-Type': 'application/json' },
      });
    }
    const filePath = path.join(process.cwd(), 'public', facture.pdfPath);
    try {
      const fileBuffer = await fs.readFile(filePath);
      return new Response(fileBuffer, {
        status: 200,
        headers: {
          'Content-Type': 'application/pdf',
          'Content-Disposition': `attachment; filename="${facture.titre || 'facture'}.pdf"`,
        },
      });
    } catch (fileErr) {
      return new Response(JSON.stringify({ error: 'Fichier PDF non trouvé' }), {
        status: 404,
        headers: { 'Content-Type': 'application/json' },
      });
    }
  } catch (e) {
    return new Response(JSON.stringify({ error: 'Erreur serveur' }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' },
    });
  }
} 