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

export const dynamic = 'force-dynamic';

// GET /api/erp/crm/contacts - List contacts
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const customerId = searchParams.get('customerId');
    const limit = parseInt(searchParams.get('limit') || '100');

    const contacts = await prisma.contact.findMany({
      where: {
        ...(customerId ? { customerId } : {})
      },
      include: {
        Customer: { select: { id: true, name: true, customerNumber: true } }
      },
      orderBy: [{ isPrimary: 'desc' }, { lastName: 'asc' }],
      take: limit
    });

    // Map to expected format for UI
    const mappedContacts = contacts.map(c => ({
      ...c,
      customer: c.Customer
    }));

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

// POST /api/erp/crm/contacts - Create contact
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { customerId, firstName, lastName, email, phone, title, department, isPrimary, notes } = body;

    if (!customerId || !firstName || !lastName) {
      return NextResponse.json({ error: 'Customer, first name, and last name are required' }, { status: 400 });
    }

    // If setting as primary, unset other primary contacts for this customer
    if (isPrimary) {
      await prisma.contact.updateMany({
        where: { customerId, isPrimary: true },
        data: { isPrimary: false }
      });
    }

    const contact = await prisma.contact.create({
      data: {
        customerId,
        firstName,
        lastName,
        email,
        phone,
        title,
        department,
        isPrimary: isPrimary || false,
        notes
      },
      include: {
        Customer: { select: { id: true, name: true } }
      }
    });

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