
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) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const { quoteId, customerEmail, customerName } = await req.json();

    const quote = await prisma.quote.findUnique({
      where: { id: quoteId },
      include: {
        user: true,
        lead: true,
      },
    });

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

    const propertyData = quote.propertyData as any;
    const projectType = quote.services && quote.services.length > 0 ? quote.services[0] : 'Project';

    // In a production environment, you would integrate with an email service like:
    // - SendGrid
    // - AWS SES
    // - Resend
    // - Nodemailer with SMTP
    
    // For now, we'll simulate sending an email
    const emailContent = {
      to: customerEmail,
      subject: `Your Quote ${quote.quoteNumber} from Quote2Contract`,
      html: `
        <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
          <h2>Hello ${customerName},</h2>
          <p>Thank you for your interest! We're pleased to provide you with the following quote:</p>
          
          <div style="background-color: #f5f5f5; padding: 20px; border-radius: 8px; margin: 20px 0;">
            <h3>Quote Details</h3>
            <p><strong>Quote Number:</strong> ${quote.quoteNumber}</p>
            <p><strong>Project Type:</strong> ${projectType}</p>
            <p><strong>Total Amount:</strong> $${quote.total.toFixed(2)}</p>
            <p><strong>Valid Until:</strong> ${quote.validUntil.toLocaleDateString()}</p>
          </div>

          ${quote.notes ? `
            <div style="margin: 20px 0;">
              <h3>Project Description</h3>
              <p>${quote.notes}</p>
            </div>
          ` : ''}

          <div style="margin: 30px 0;">
            <p>To accept or review this quote, please log in to your customer portal:</p>
            <a href="${process.env.NEXTAUTH_URL}/customer/dashboard" 
               style="display: inline-block; background-color: #2563eb; color: white; padding: 12px 24px; text-decoration: none; border-radius: 6px; margin: 10px 0;">
              View Quote
            </a>
          </div>

          ${quote.termsConditions ? `
            <div style="margin: 20px 0; font-size: 12px; color: #666;">
              <h4>Terms & Conditions</h4>
              <p>${quote.termsConditions}</p>
            </div>
          ` : ''}

          <p>If you have any questions, please don't hesitate to contact us.</p>
          
          <p style="margin-top: 30px;">Best regards,<br>Quote2Contract Team</p>
        </div>
      `,
    };

    console.log('Email would be sent:', emailContent);

    // TODO: Integrate with actual email service
    // Example with SendGrid:
    // await sendgrid.send(emailContent);

    return NextResponse.json({ 
      success: true, 
      message: 'Email sent successfully (simulated)' 
    });
  } catch (error) {
    console.error('Error sending email:', error);
    return NextResponse.json(
      { error: 'Failed to send email' },
      { status: 500 }
    );
  }
}
