import { NextRequest, NextResponse } from 'next/server'
import type { EmailTemplate, Customer } from '@/types/email'
import { sendCampaignEmails, verifyEmailConnection } from '@/lib/emailService'

interface SendEmailRequest {
  template: EmailTemplate
  customers: Customer[]
  selectedCustomerIds: string[]
}

export async function POST(request: NextRequest) {
  try {
    const body: SendEmailRequest = await request.json()
    const { template, customers, selectedCustomerIds } = body

    // Debug logging for received data
    console.log('📥 API Route - Received data:', {
      templateLogoUrl: template?.logoUrl,
      hasTemplateLogoUrl: !!template?.logoUrl,
      templateLogoUrlLength: template?.logoUrl?.length,
      templateLogoUrlStartsWithData: template?.logoUrl?.startsWith('data:'),
      templateLogoUrlType: typeof template?.logoUrl
    })

    if (!template || !customers || !selectedCustomerIds || selectedCustomerIds.length === 0) {
      return NextResponse.json(
        { error: 'Missing required data: template, customers, or selectedCustomerIds' },
        { status: 400 }
      )
    }

    // Verify email service connection first
    const isConnected = await verifyEmailConnection()
    if (!isConnected) {
      return NextResponse.json(
        { error: 'Email service not available. Please check SMTP configuration.' },
        { status: 503 }
      )
    }

    console.log('📧 Starting real email campaign:', {
      templateSubject: template.subject,
      customerCount: selectedCustomerIds.length,
      customers: customers.filter(c => selectedCustomerIds.includes(c.id))
        .map(c => ({ id: c.id, email: c.email, name: c.name }))
    })

    // Send real emails using email service
    const result = await sendCampaignEmails(template, customers, selectedCustomerIds)

    if (result.success) {
      return NextResponse.json({
        success: true,
        message: result.message,
        results: result.results,
        summary: result.summary
      })
    } else {
      return NextResponse.json({
        success: false,
        error: 'Campaign failed',
        message: result.message,
        results: result.results,
        summary: result.summary
      }, { status: 500 })
    }

  } catch (error) {
    console.error('💥 Error in email send API:', error)
    return NextResponse.json(
      { 
        error: 'Internal server error',
        message: error instanceof Error ? error.message : 'Unknown error'
      },
      { status: 500 }
    )
  }
}
