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

export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const {
      projectType,
      material,
      budgetRange,
      location,
      contactMethod,
      contactInfo,
      additionalNotes,
    } = body;

    // Validate required fields
    if (!projectType || !location?.address || !contactMethod || !contactInfo?.name) {
      return NextResponse.json(
        { error: 'Missing required fields' },
        { status: 400 }
      );
    }

    // Check if a user with this email exists
    let existingUser = null;
    if (contactInfo.email) {
      existingUser = await prisma.user.findUnique({
        where: { email: contactInfo.email },
      });
    }

    // Create a lead record
    const lead = await prisma.lead.create({
      data: {
        firstName: contactInfo.name.split(' ')[0] || contactInfo.name,
        lastName: contactInfo.name.split(' ').slice(1).join(' ') || '',
        email: contactInfo.email || `${Date.now()}@placeholder.com`,
        phone: contactInfo.phone || '',
        address: location.address,
        city: location.address.split(',').slice(-2, -1)[0]?.trim() || '',
        state: location.address.split(',').slice(-1)[0]?.trim() || '',
        zipCode: '',
        source: 'WEB',
        services: [projectType],
        description: `${projectType} project - ${material || 'Not specified'}\nBudget: ${budgetRange?.label || 'Not specified'}\nPreferred Contact: ${contactMethod}\n\nAdditional Notes: ${additionalNotes || 'None'}`,
        budget: budgetRange?.label || 'Not specified',
        status: 'NEW',
        priority: 'MEDIUM',
        createdById: existingUser?.id || '1', // Default to system if no user found
      },
    });

    // Create audit log
    await prisma.auditLog.create({
      data: {
        action: 'LEAD_CREATED',
        entityType: 'Lead',
        entityId: lead.id,
        newData: {
          leadId: lead.id,
          description: `New quote request via wizard: ${projectType} - ${contactInfo.name}`,
        },
        metadata: {
          projectType,
          material,
          contactMethod,
          location: location.address,
          budgetRange: budgetRange?.label,
        },
        userId: existingUser?.id || '1',
      },
    });

    // TODO: Send notification to admin/matching contractors
    // TODO: Send confirmation email/SMS to customer

    return NextResponse.json({
      success: true,
      leadId: lead.id,
      message: 'Quote request submitted successfully',
    });
  } catch (error) {
    console.error('Error creating quote request:', error);
    return NextResponse.json(
      { error: 'Failed to submit quote request' },
      { status: 500 }
    );
  }
}
