import { NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "../../../auth/authOptions";
import { prisma } from "@/lib/prisma";
import { DocumentType } from "@/types/types";
import { mkdir, writeFile } from "fs/promises";
import path from "path";

export async function GET(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const session = await getServerSession(authOptions);
  if (!session) {
    return NextResponse.json({ error: "Non autorisé" }, { status: 401 });
  }

  try {
    const resolvedParams = await params;
    const clientId = parseInt(resolvedParams.id);
    
    // Vérifier que le client existe
    const client = await prisma.client.findUnique({
      where: { id: clientId }
    });

    if (!client) {
      return NextResponse.json({ error: "Client non trouvé" }, { status: 404 });
    }

    // Récupérer les documents d'identité du client
    const identityDocuments = await prisma.document.findMany({
      where: {
        clientId: clientId,
        documentType: {
          in: [
            DocumentType.IDENTITY_CARD,
            DocumentType.PASSPORT,
            DocumentType.DAY_PERMIT,
            DocumentType.APPOINTMENT_DEED
          ]
        }
      },
      orderBy: { uploadDate: 'desc' }
    });

    return NextResponse.json(identityDocuments);
  } catch (error) {
    console.error('Erreur lors de la récupération des documents d\'identité:', error);
    return NextResponse.json(
      { error: "Erreur serveur" },
      { status: 500 }
    );
  }
}

// Handler POST pour upload de document d'identité (compatible Next.js App Router)
export async function POST(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  console.log('POST /api/clients/[id]/identity-documents appelé');
  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');
    if (!file || !(file instanceof File)) {
      console.error('Fichier manquant ou invalide');
      return NextResponse.json({ error: 'Fichier manquant' }, { 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: 'identity',
        uploadDate: new Date(),
      },
    });
    console.log('Document créé en base :', document);
    return NextResponse.json(document, { status: 201 });
  } catch (e) {
    console.error("Erreur lors de l'upload du document d'identité", e);
    return NextResponse.json({ error: "Erreur lors de l'upload du document d'identité" }, { status: 500 });
  }
} 