import { NextResponse } from 'next/server';
import prisma from '../../../../../lib/prisma';
import fs from 'fs/promises';
import path from 'path';

export async function GET(request: Request, context: { params: Promise<{ id: string }> }) {
  try {
    const params = await context.params;
    const { searchParams } = new URL(request.url);
    const downloadId = searchParams.get('download');

    if (downloadId) {
      const doc = await prisma.customerDocument.findUnique({
        where: { id: parseInt(downloadId) }
      });
      if (!doc) return new NextResponse('Not found', { status: 404 });

      const filePath = path.join(process.cwd(), 'uploads', 'customers', params.id, doc.savedName);
      const fileBuffer = await fs.readFile(filePath);

      return new NextResponse(fileBuffer, {
        headers: {
          'Content-Type': doc.fileType,
          'Content-Disposition': `attachment; filename="${doc.fileName}"`,
        },
      });
    }

    const documents = await prisma.customerDocument.findMany({
      where: { customerId: parseInt(params.id) },
      orderBy: { createdAt: 'desc' }
    });
    return NextResponse.json(documents);
  } catch (error) {
    return NextResponse.json({ error: 'Ladefehler' }, { status: 500 });
  }
}

export async function POST(request: Request, context: { params: Promise<{ id: string }> }) {
  try {
    const params = await context.params;
    const formData = await request.formData();
    const file = formData.get('file') as File;
    if (!file) return NextResponse.json({ error: 'No file uploaded' }, { status: 400 });

    const buffer = Buffer.from(await file.arrayBuffer());
    const savedName = `${Date.now()}_${file.name.replace(/[^a-zA-Z0-9.-]/g, '_')}`;
    const uploadDir = path.join(process.cwd(), 'uploads', 'customers', params.id);

    await fs.mkdir(uploadDir, { recursive: true });
    await fs.writeFile(path.join(uploadDir, savedName), buffer);

    const doc = await prisma.customerDocument.create({
      data: {
        customerId: parseInt(params.id),
        fileName: file.name,
        savedName: savedName,
        fileSize: file.size,
        fileType: file.type
      }
    });

    return NextResponse.json(doc);
  } catch (error) {
    console.error(error);
    return NextResponse.json({ error: 'Upload fehlgeschlagen' }, { status: 500 });
  }
}

export async function DELETE(request: Request, context: { params: Promise<{ id: string }> }) {
  try {
    const params = await context.params;
    const { searchParams } = new URL(request.url);
    const docId = searchParams.get('docId');
    if (!docId) return NextResponse.json({ error: 'ID fehlt' }, { status: 400 });

    const doc = await prisma.customerDocument.findUnique({
      where: { id: parseInt(docId) }
    });

    if (doc) {
      const filePath = path.join(process.cwd(), 'uploads', 'customers', params.id, doc.savedName);
      try {
        await fs.unlink(filePath);
      } catch(e) {
        // ignore if file doesn't exist
      }
      await prisma.customerDocument.delete({ where: { id: parseInt(docId) } });
    }

    return NextResponse.json({ success: true });
  } catch (error) {
    return NextResponse.json({ error: 'Löschen fehlgeschlagen' }, { status: 500 });
  }
}
