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

export async function POST(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions);

    if (!session || session.user.role === 'CUSTOMER') {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const body = await req.json();
    const { customerInfo, measurements, quoteDetails, totalAmount, sendEmail } = body;

    // Check if customer exists, if not create one
    let customer = await prisma.user.findUnique({
      where: { email: customerInfo.email },
    });

    if (!customer) {
      customer = await prisma.user.create({
        data: {
          email: customerInfo.email,
          firstName: customerInfo.firstName,
          lastName: customerInfo.lastName,
          name: `${customerInfo.firstName} ${customerInfo.lastName}`,
          phone: customerInfo.phone || null,
          companyName: customerInfo.companyName || null,
          role: 'CUSTOMER',
          // Customer accounts created via quote don't have passwords (admin-created)
          password: '', 
        },
      });
    }

    // Create a lead for this quote
    const leadCount = await prisma.lead.count();
    const lead = await prisma.lead.create({
      data: {
        firstName: customerInfo.firstName,
        lastName: customerInfo.lastName,
        email: customerInfo.email,
        phone: customerInfo.phone || '',
        address: customerInfo.address || '',
        city: customerInfo.city || '',
        state: customerInfo.state || '',
        zipCode: customerInfo.zipCode || '',
        source: 'WEB',
        services: [quoteDetails.projectType],
        description: quoteDetails.description,
        status: 'QUOTED',
        createdById: session.user.id,
      },
    });

    // Generate quote number
    const quoteCount = await prisma.quote.count();
    const quoteNumber = `Q2C-${new Date().getFullYear()}-${String(quoteCount + 1).padStart(4, '0')}`;

    // Calculate valid until date (default 30 days if not provided)
    const validUntil = quoteDetails.validUntil 
      ? new Date(quoteDetails.validUntil)
      : new Date(Date.now() + 30 * 24 * 60 * 60 * 1000);

    // Prepare line items
    const lineItems = measurements.map((m: any) => ({
      type: m.type,
      area: m.area,
      rate: m.price / m.area,
      amount: m.price,
      notes: m.notes,
    }));

    // Create quote
    const quote = await prisma.quote.create({
      data: {
        quoteNumber,
        leadId: lead.id,
        userId: customer.id,
        services: [quoteDetails.projectType],
        propertyData: {
          address: customerInfo.address,
          measurements: measurements,
        },
        lineItems: lineItems,
        subtotal: totalAmount,
        discounts: 0,
        taxes: 0,
        total: totalAmount,
        status: sendEmail ? 'SENT' : 'DRAFT',
        validUntil,
        notes: quoteDetails.description,
        termsConditions: quoteDetails.terms,
        sentAt: sendEmail ? new Date() : null,
      },
    });

    // Send email if requested
    if (sendEmail) {
      try {
        await fetch(`${process.env.NEXTAUTH_URL || 'http://localhost:3000'}/api/quotes/send-email`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            quoteId: quote.id,
            customerEmail: customer.email,
            customerName: customer.name,
          }),
        });
      } catch (emailError) {
        console.error('Failed to send email:', emailError);
        // Don't fail the quote creation if email fails
      }
    }

    return NextResponse.json({ 
      success: true, 
      quote,
      message: sendEmail ? 'Quote created and email sent' : 'Quote created successfully'
    });
  } catch (error) {
    console.error('Error creating quote:', error);
    return NextResponse.json(
      { error: 'Failed to create quote' },
      { status: 500 }
    );
  }
}

export async function GET(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions);

    if (!session) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    // For customers, only show their quotes
    const where = session.user.role === 'CUSTOMER' 
      ? { userId: session.user.id }
      : {};

    const quotes = await prisma.quote.findMany({
      where,
      include: {
        user: {
          select: {
            name: true,
            email: true,
            companyName: true,
          },
        },
        lead: {
          select: {
            firstName: true,
            lastName: true,
            email: true,
          },
        },
      },
      orderBy: {
        createdAt: 'desc',
      },
    });

    return NextResponse.json({ quotes });
  } catch (error) {
    console.error('Error fetching quotes:', error);
    return NextResponse.json(
      { error: 'Failed to fetch quotes' },
      { status: 500 }
    );
  }
}
