import { NextResponse } from 'next/server';
import { ComparisonEmail } from '../../../../../lib/mailer';

export async function POST(request) {
  try {
    const body = await request.json();
    const { 
      comparisonType, 
      selectedItems, 
      aiResults, 
      userData
    } = body;

    // Validate required data
    if (!userData?.email) {
      return NextResponse.json(
        { success: false, message: 'User email is required' },
        { status: 400 }
      );
    }

    if (!selectedItems || selectedItems.length === 0) {
      return NextResponse.json(
        { success: false, message: 'No comparison items provided' },
        { status: 400 }
      );
    }

    const info = await ComparisonEmail(comparisonType, selectedItems, aiResults, userData)

    return NextResponse.json({
      success: true,
      message: 'Email sent successfully',
      messageId: info.messageId,
      comparisonId: aiResults?.comparison_id,
    });

  } catch (error) {
    console.error('Error sending email:', error);
    
    return NextResponse.json(
      { 
        success: false, 
        message: 'Failed to send email',
        error: process.env.NODE_ENV === 'development' ? error.message : undefined 
      },
      { status: 500 }
    );
  }
}