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

export async function POST(request: Request) {
  try {
    const data = await request.json();

    // Find the first admin user to assign as creator
    const adminUser = await prisma.user.findFirst({
      where: {
        role: 'ADMIN',
      },
    });

    if (!adminUser) {
      return NextResponse.json(
        { error: 'System configuration error' },
        { status: 500 }
      );
    }

    // Create a lead from the landing page submission
    const lead = await prisma.lead.create({
      data: {
        firstName: data.fullName.split(' ')[0] || data.fullName,
        lastName: data.fullName.split(' ').slice(1).join(' ') || '',
        email: data.email,
        phone: data.phone,
        address: data.city, // Use city as address for now
        city: data.city,
        state: 'ZA', // South Africa
        zipCode: '0000', // Default
        source: 'WEB',
        services: [data.trade],
        description: `Landing page submission from ${data.companyName}. Trade: ${data.trade}`,
        budget: null,
        timeline: null,
        status: 'NEW',
        score: 0.0,
        priority: 'HIGH', // Landing page leads are high priority
        createdById: adminUser.id,
      },
    });

    // Create audit log
    await prisma.auditLog.create({
      data: {
        userId: adminUser.id,
        entityType: 'lead',
        entityId: lead.id,
        action: 'create',
        newData: lead,
        metadata: {
          source: 'landing_page',
          companyName: data.companyName,
          timestamp: new Date().toISOString(),
        },
      },
    });

    // TODO: Send notification email to sales team
    // TODO: Send confirmation email/SMS to contractor

    return NextResponse.json({ success: true, leadId: lead.id }, { status: 201 });
  } catch (error) {
    console.error('Error creating landing page lead:', error);
    return NextResponse.json(
      { error: 'Failed to submit form' },
      { status: 500 }
    );
  }
}
