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

// POST /api/quotes/auto-generate - Auto-generate quote using aerial calculation
export async function POST(request: NextRequest) {
  try {
    const session = await getServerSession();
    if (!session?.user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const body = await request.json();
    const { leadId, serviceType, roofMaterial, condition } = body;

    const lead = await prisma.lead.findUnique({
      where: { id: leadId },
    });

    if (!lead) {
      return NextResponse.json({ error: 'Lead not found' }, { status: 404 });
    }

    // Step 1: Calculate area using aerial imagery
    const aerialResponse = await fetch(
      `${process.env.NEXTAUTH_URL}/api/aerial/calculate`,
      {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          address: lead.address,
          latitude: lead.latitude,
          longitude: lead.longitude,
          serviceType,
        }),
      }
    );

    const aerialData = await aerialResponse.json();

    // Step 2: Get pricing rates
    const pricingRate = await prisma.pricingRate.findUnique({
      where: { serviceType },
    });

    if (!pricingRate) {
      return NextResponse.json(
        { error: 'Pricing rate not found for service type' },
        { status: 404 }
      );
    }

    // Step 3: Calculate pricing
    const area = aerialData.calculations.roofArea || 180; // Default fallback
    const basePrice = area * pricingRate.rate;

    // Material multiplier
    const materialMultipliers: any = {
      asphalt: 1.0,
      metal: 1.3,
      tile: 1.5,
      slate: 2.0,
    };
    const materialMultiplier = materialMultipliers[roofMaterial] || 1.0;

    // Condition multiplier
    const conditionMultipliers: any = {
      new: 1.0,
      good: 1.1,
      fair: 1.2,
      poor: 1.4,
    };
    const conditionMultiplier = conditionMultipliers[condition] || 1.0;

    const subtotal = basePrice * materialMultiplier * conditionMultiplier;
    const taxes = subtotal * 0.15; // 15% VAT
    const total = subtotal + taxes;

    // Step 4: Create quote
    const quoteNumber = `Q${Date.now()}`;
    
    const quote = await prisma.quote.create({
      data: {
        quoteNumber,
        leadId,
        userId: session.user.id,
        propertyData: {
          address: lead.address,
          area: area,
          aerialData,
        },
        services: [serviceType],
        lineItems: [
          {
            description: `${serviceType} - ${area.toFixed(2)} sq m`,
            quantity: area,
            rate: pricingRate.rate,
            amount: basePrice,
          },
          {
            description: `Material: ${roofMaterial}`,
            amount: basePrice * (materialMultiplier - 1),
          },
          {
            description: `Condition adjustment: ${condition}`,
            amount: basePrice * materialMultiplier * (conditionMultiplier - 1),
          },
        ],
        subtotal,
        taxes,
        total,
        validUntil: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
        region: lead.region,
        status: 'DRAFT',
      },
    });

    // Step 5: Find matching contractors
    await fetch(`${process.env.NEXTAUTH_URL}/api/matching/contractors`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ leadId }),
    });

    return NextResponse.json({
      success: true,
      quote,
      aerialData,
    });
  } catch (error) {
    console.error('Error auto-generating quote:', error);
    return NextResponse.json(
      { error: 'Failed to generate quote' },
      { status: 500 }
    );
  }
}
