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

export async function GET(request: Request, context: { params: Promise<{ id: string }> }) {
  try {
    const params = await context.params;
    const contracts = await prisma.contract.findMany({
      where: { customerId: parseInt(params.id) },
      orderBy: { createdAt: 'desc' }
    });
    return NextResponse.json(contracts);
  } 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 data = await request.json();
    
    const contract = await prisma.contract.create({
      data: {
        customerId: parseInt(params.id),
        title: data.title,
        description: data.description || '',
        startDate: new Date(data.startDate),
        endDate: data.endDate ? new Date(data.endDate) : null,
        monthlyPrice: parseFloat(data.monthlyPrice) || 0,
        status: data.status || 'ACTIVE'
      }
    });

    return NextResponse.json(contract);
  } catch (error) {
    return NextResponse.json({ error: 'Erstellen fehlgeschlagen' }, { status: 500 });
  }
}

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

    await prisma.contract.delete({
      where: { id: parseInt(contractId) }
    });

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