import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { writeFile, mkdir } from 'fs/promises';
import path from 'path';

export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const resolvedParams = await params;
  const clientId = parseInt(resolvedParams.id);
  const { searchParams } = new URL(request.url);
  const section = searchParams.get('section');
  if (isNaN(clientId)) {
    return NextResponse.json({ error: 'ID client invalide' }, { status: 400 });
  }
  try {
    const where = section
      ? { clientId, documentCategory: section }
      : { clientId };
    const documents = await prisma.document.findMany({
      where,
      orderBy: { uploadDate: 'desc' },
    });
    // Ajoute un champ downloadUrl pour chaque document
    const docsWithUrl = documents.map(doc => ({ ...doc, downloadUrl: `/api/clients/${clientId}/documents/${doc.id}/download` }));
    return NextResponse.json(docsWithUrl, { status: 200 });
  } catch (e) {
    return NextResponse.json({ error: 'Erreur lors de la récupération des documents' }, { status: 500 });
  }
}

// Handler POST pour upload de document pour toutes les sections (compatible App Router)
export async function POST(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const resolvedParams = await params;
  const clientId = parseInt(resolvedParams.id);
  if (isNaN(clientId)) {
    console.error('ID client invalide');
    return NextResponse.json({ error: 'ID client invalide' }, { status: 400 });
  }
  try {
    const formData = await request.formData();
    const file = formData.get('file');
    const section = formData.get('section');
    console.log('Contenu formData:', { file, section });
    if (!file || typeof file !== 'object' || !('name' in file) || typeof file.arrayBuffer !== 'function') {
      console.error('Fichier manquant ou invalide', { fileType: typeof file, file });
      return NextResponse.json({ error: 'Fichier manquant' }, { status: 400 });
    }
    if (!section || typeof section !== 'string') {
      console.error('Section manquante ou invalide', { section });
      return NextResponse.json({ error: 'Section manquante' }, { status: 400 });
    }
    const buffer = Buffer.from(await file.arrayBuffer());
    const filename = file.name.replaceAll(' ', '_');
    const uploadDir = path.join(process.cwd(), 'public', 'uploads');
    await mkdir(uploadDir, { recursive: true });
    const filePath = path.join(uploadDir, filename);
    await writeFile(filePath, buffer);
    console.log('Fichier uploadé à :', filePath);
    const document = await prisma.document.create({
      data: {
        name: file.name,
        fileType: file.type,
        path: `/uploads/${filename}`,
        client: { connect: { id: clientId } },
        documentCategory: section,
        uploadDate: new Date(),
      },
    });
    console.log('Document créé en base :', document);
    return NextResponse.json(document, { status: 201 });
  } catch (e: any) {
    console.error("Erreur lors de l'upload du document", e, e?.stack);
    return NextResponse.json({ error: "Erreur lors de l'upload du document", details: e?.message, stack: e?.stack }, { status: 500 });
  }
}console.log('[authOptions] NEXTAUTH_SECRET loaded:', process.env.NEXTAUTH_SECRET ? process.env.NEXTAUTH_SECRET.slice(0, 5) + '...' : 'undefined');