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

export async function GET() {
  try {
    const customers = await prisma.customer.findMany({ 
      orderBy: { businessName: 'asc' },
      include: {
        _count: { select: { billingOrders: true, shippingOrders: true } },
        subCustomers: true,
      }
    });
    return NextResponse.json(customers);
  } catch (error: any) {
    console.error('GET /api/customers error:', error);
    return NextResponse.json({ error: error.message || 'Error fetching customers' }, { status: 500 });
  }
}

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { 
      businessName, contactName, taxId, 
      address, address2, city, state, zipCode, country, 
      phone, email, salesRep, 
      isBilling, isShipping, isMaster,
      customerType, // 'billing' | 'shipping' | 'master' | 'all'
      parentId
    } = body;

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

    // Resolve booleans from customerType helper if sent
    let resolvedIsBilling = isBilling ?? false;
    let resolvedIsShipping = isShipping ?? true;
    let resolvedIsMaster = isMaster ?? false;

    if (customerType === 'billing') { resolvedIsBilling = true; resolvedIsShipping = false; resolvedIsMaster = false; }
    else if (customerType === 'shipping') { resolvedIsBilling = false; resolvedIsShipping = true; resolvedIsMaster = false; }
    else if (customerType === 'master') { resolvedIsBilling = false; resolvedIsShipping = false; resolvedIsMaster = true; }
    else if (customerType === 'all') { resolvedIsBilling = true; resolvedIsShipping = true; resolvedIsMaster = true; }

    const customer = await prisma.customer.create({
      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: resolvedIsBilling,
        isShipping: resolvedIsShipping,
        isMaster: resolvedIsMaster,
        parentId: parentId || null,
      }
    });
    return NextResponse.json(customer, { status: 201 });
  } catch (error: any) {
    console.error('POST /api/customers error:', error);
    return NextResponse.json({ error: error.message || 'Error creating customer' }, { status: 500 });
  }
}
