import { NextRequest, NextResponse } from 'next/server'
import { processSupportEmail, sendEmail } from '@/lib/ai/email'
import { db } from '@/lib/db'

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { to, subject, message, userId } = body as {
      to: string
      subject: string
      message: string
      userId?: string
    }

    if (!to || !subject || !message) {
      return NextResponse.json(
        { error: 'Recipient email, subject, and message are required.' },
        { status: 400 }
      )
    }

    // Process the support email with AI
    const analysis = await processSupportEmail(to, subject, message)

    // Log the email
    try {
      await db.emailLog.create({
        data: {
          to,
          subject: `[AI Support] ${subject}`,
          body: `Original:\n${message}\n\nAI Category: ${analysis.category}\nAI Priority: ${analysis.priority}\nAI Suggested Response:\n${analysis.suggestedResponse}`,
          status: 'sent',
        },
      })
    } catch {
      // Non-critical
    }

    // Try to send the AI-processed response
    const sent = await sendEmail(to, `Re: ${subject}`, analysis.suggestedResponse)

    return NextResponse.json({
      success: true,
      analysis: {
        category: analysis.category,
        priority: analysis.priority,
      },
      response: analysis.suggestedResponse,
      emailSent: sent,
      message: sent
        ? 'AI-processed response sent successfully.'
        : 'Response generated but email not configured. See draft below.',
    })
  } catch (error) {
    console.error('Email support error:', error instanceof Error ? error.message : error)
    return NextResponse.json(
      { error: 'Failed to process support email.' },
      { status: 500 }
    )
  }
}
