import { NextRequest, NextResponse } from 'next/server'
import { mailgunService } from '@/lib/mailgun'
import { z } from 'zod'

export const runtime = 'nodejs'

const contactSchema = z.object({
  name: z.string().min(1, 'Name is required').max(100),
  email: z.string().email('Invalid email address'),
  subject: z.string().min(1, 'Subject is required').max(200),
  message: z.string().min(10, 'Message must be at least 10 characters').max(5000)
})

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()

    // Validate input
    const validationResult = contactSchema.safeParse(body)
    if (!validationResult.success) {
      return NextResponse.json({
        success: false,
        error: 'Invalid form data',
        details: validationResult.error.errors
      }, { status: 400 })
    }

    const { name, email, subject, message } = validationResult.data

    // Basic spam prevention - check for common spam indicators
    const spamIndicators = [
      message.includes('http://'),
      message.includes('https://'),
      message.includes('www.'),
      message.includes('bitcoin'),
      message.includes('cryptocurrency'),
      message.length < 10,
      name.length < 2
    ]

    const spamScore = spamIndicators.filter(Boolean).length
    if (spamScore >= 2) {
      return NextResponse.json({
        success: false,
        error: 'Message flagged as potential spam'
      }, { status: 400 })
    }

    // Send email using Mailgun
    const emailResult = await mailgunService.sendContactForm({
      name,
      email,
      subject,
      message
    })

    if (emailResult.success) {
      return NextResponse.json({
        success: true,
        message: 'Your message has been sent successfully!'
      })
    } else {
      console.error('Contact form email failed:', emailResult.error)
      return NextResponse.json({
        success: false,
        error: 'Failed to send message. Please try again later.'
      }, { status: 500 })
    }

  } catch (error) {
    console.error('Contact form error:', error)
    return NextResponse.json({
      success: false,
      error: 'Internal server error'
    }, { status: 500 })
  }
}