import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';
import { z } from 'zod';
import { validateBody } from '@/lib/api-validation';

export const dynamic = 'force-dynamic';

const createCustomerSchema = z.object({
  name: z.string().min(1, 'Customer name is required').max(200),
  email: z.string().email().max(255).optional().nullable(),
  phone: z.string().max(50).optional().nullable(),
  address: z.string().max(500).optional().nullable(),
  city: z.string().max(100).optional().nullable(),
  state: z.string().max(100).optional().nullable(),
  country: z.string().max(100).optional().nullable(),
  postalCode: z.string().max(20).optional().nullable(),
  industry: z.string().max(200).optional().nullable(),
  website: z.string().max(500).optional().nullable(),
  notes: z.string().max(2000).optional().nullable(),
});

// GET /api/erp/crm/customers - List all customers
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const search = searchParams.get('search') || '';
    const status = searchParams.get('status');
    const limit = parseInt(searchParams.get('limit') || '50');

    const customers = await prisma.customer.findMany({
      where: {
        ...(search ? {
          OR: [
            { name: { contains: search, mode: 'insensitive' } },
            { email: { contains: search, mode: 'insensitive' } },
            { customerNumber: { contains: search, mode: 'insensitive' } }
          ]
        } : {}),
        ...(status ? { status } : {})
      },
      include: {
        contacts: { take: 3 },
        _count: {
          select: { salesOrders: true, opportunities: true, contacts: true }
        }
      },
      orderBy: { createdAt: 'desc' },
      take: limit
    });

    return NextResponse.json({ customers });
  } catch (error) {
    console.error('Customers list error:', error);
    return NextResponse.json({ error: 'Failed to fetch customers' }, { status: 500 });
  }
}

// POST /api/erp/crm/customers - Create a new customer
export async function POST(request: NextRequest) {
  try {
    const result = await validateBody(request, createCustomerSchema);
    if (result.error) return result.error;
    const { name, email, phone, address, city, state, country, postalCode, industry, website, notes } = result.data;

    // Generate customer number
    const count = await prisma.customer.count();
    const customerNumber = `CUST-${String(count + 1).padStart(5, '0')}`;

    // Build address JSON
    const addressData = address || city || state || country || postalCode ? {
      street: address || '',
      city: city || '',
      state: state || '',
      country: country || '',
      postalCode: postalCode || ''
    } : undefined;

    const customer = await prisma.customer.create({
      data: {
        customerNumber,
        name,
        email,
        phone,
        ...(addressData ? { billingAddress: addressData, shippingAddress: addressData } : {}),
        industry,
        website,
        notes,
        status: 'active'
      }
    });

    return NextResponse.json({ customer }, { status: 201 });
  } catch (error) {
    console.error('Create customer error:', error);
    return NextResponse.json({ error: 'Failed to create customer' }, { status: 500 });
  }
}
