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

export const dynamic = 'force-dynamic';

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

    const leads = await prisma.lead.findMany({
      where: {
        ...(status ? { status } : {}),
        ...(source ? { source } : {})
      },
      include: {
        customer: { select: { id: true, name: true } }
      },
      orderBy: { createdAt: 'desc' },
      take: limit
    });

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

// POST /api/erp/crm/leads - Create lead
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { companyName, contactName, email, phone, source, notes, estimatedValue } = body;

    if (!companyName && !contactName) {
      return NextResponse.json({ error: 'Company or contact name required' }, { status: 400 });
    }

    const lead = await prisma.lead.create({
      data: {
        companyName,
        contactName,
        email,
        phone,
        source: source || 'website',
        notes,
        estimatedValue: estimatedValue ? parseFloat(estimatedValue) : null,
        status: 'new'
      }
    });

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