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

export async function GET(_: Request, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params;
    const customer = await prisma.customer.findUnique({ 
      where: { id },
      include: {
        billingOrders: { select: { id: true, po: true, orderNumber: true, deliveryDate: true, status: true }, take: 10, orderBy: { createdAt: 'desc' } },
        shippingOrders: { select: { id: true, po: true, orderNumber: true, deliveryDate: true, status: true }, take: 10, orderBy: { createdAt: 'desc' } },
      }
    });
    if (!customer) return NextResponse.json({ error: 'Customer not found' }, { status: 404 });
    return NextResponse.json(customer);
  } catch (error: any) {
    console.error('GET /api/customers/[id] error:', error);
    return NextResponse.json({ error: error.message || 'Error fetching customer' }, { status: 500 });
  }
}

export async function PUT(request: Request, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params;
    const body = await request.json();
    const { 
      businessName, contactName, taxId, 
      address, address2, city, state, zipCode, country, 
      phone, email, salesRep, 
      isBilling, isShipping, isMaster, parentId
    } = body;

    if (!businessName?.trim()) {
      return NextResponse.json({ error: 'El nombre de empresa es requerido' }, { status: 400 });
    }

    const customer = await prisma.customer.update({
      where: { id },
      data: { 
        businessName: businessName.trim(), 
        contactName: contactName?.trim() || null,
        taxId: taxId?.trim() || null,
        address: address?.trim() || null,
        address2: address2?.trim() || null,
        city: city?.trim() || null,
        state: state?.trim() || null,
        zipCode: zipCode?.trim() || null,
        country: country?.trim() || 'US',
        phone: phone?.trim() || null,
        email: email?.trim() || null,
        salesRep: salesRep?.trim() || null,
        isBilling: isBilling ?? false,
        isShipping: isShipping ?? true,
        isMaster: isMaster ?? false,
        parentId: parentId || null,
      }
    });
    return NextResponse.json(customer);
  } catch (error: any) {
    console.error('PUT /api/customers/[id] error:', error);
    return NextResponse.json({ error: error.message || 'Error updating customer' }, { status: 500 });
  }
}

export async function DELETE(_: Request, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params;

    // Check if customer has orders before deleting
    const orderCount = await prisma.order.count({
      where: { OR: [{ billingCustomerId: id }, { shippingCustomerId: id }] }
    });

    if (orderCount > 0) {
      return NextResponse.json({ 
        error: `No se puede eliminar: este cliente tiene ${orderCount} orden(es) asociada(s). Elimina primero las órdenes.` 
      }, { status: 409 });
    }

    await prisma.customer.delete({ where: { id } });
    return NextResponse.json({ success: true });
  } catch (error: any) {
    console.error('DELETE /api/customers/[id] error:', error);
    return NextResponse.json({ error: error.message || 'Error deleting customer' }, { status: 500 });
  }
}
