import { NextRequest, NextResponse } from 'next/server'
import { newsletterSchema } from '@/lib/validation-schemas'
import { rateLimit } from '@/lib/rate-limiter'
import { z } from 'zod'

// Subscribe to newsletter using email service
async function subscribeToNewsletter(data: z.infer<typeof newsletterSchema>) {
  // Try Mailchimp first
  if (process.env.MAILCHIMP_API_KEY && process.env.MAILCHIMP_AUDIENCE_ID) {
    try {
      const dc = process.env.MAILCHIMP_API_KEY.split('-')[1]
      const url = `https://${dc}.api.mailchimp.com/3.0/lists/${process.env.MAILCHIMP_AUDIENCE_ID}/members`

      const response = await fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${process.env.MAILCHIMP_API_KEY}`,
        },
        body: JSON.stringify({
          email_address: data.email,
          status: 'subscribed',
          merge_fields: data.name ? {
            FNAME: data.name.split(' ')[0],
            LNAME: data.name.split(' ').slice(1).join(' ') || '',
          } : {},
          tags: ['Portfolio Website'],
        }),
      })

      if (!response.ok) {
        const error = await response.json()
        console.error('Mailchimp API error:', error)
        
        // Check if already subscribed
        if (error.title === 'Member Exists') {
          return { success: true, provider: 'mailchimp', alreadySubscribed: true }
        }
        
        throw new Error('Failed to subscribe via Mailchimp')
      }

      return { success: true, provider: 'mailchimp' }
    } catch (error) {
      console.error('Mailchimp error:', error)
    }
  }

  // Try ConvertKit
  if (process.env.CONVERTKIT_API_KEY && process.env.CONVERTKIT_FORM_ID) {
    try {
      const url = `https://api.convertkit.com/v3/forms/${process.env.CONVERTKIT_FORM_ID}/subscribe`

      const response = await fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          api_key: process.env.CONVERTKIT_API_KEY,
          email: data.email,
          first_name: data.name?.split(' ')[0],
        }),
      })

      if (!response.ok) {
        const error = await response.json()
        console.error('ConvertKit API error:', error)
        throw new Error('Failed to subscribe via ConvertKit')
      }

      return { success: true, provider: 'convertkit' }
    } catch (error) {
      console.error('ConvertKit error:', error)
    }
  }

  // Fallback: Store locally or send email notification
  console.log('📧 Newsletter subscription (no service configured):', data)
  
  // TODO: Store in database
  // await db.newsletterSubscribers.create({ data })

  return { success: true, provider: 'local' }
}

export async function POST(request: NextRequest) {
  try {
    // Rate limiting check
    const ip = request.headers.get('x-forwarded-for') || request.headers.get('x-real-ip') || 'unknown'
    const rateLimitResult = await rateLimit(ip, 'newsletter')
    
    if (!rateLimitResult.success) {
      return NextResponse.json(
        { 
          error: 'Too many subscription attempts. Please try again later.',
          retryAfter: rateLimitResult.retryAfter,
        },
        { status: 429 }
      )
    }

    // Parse and validate request body
    const body = await request.json()
    const validationResult = newsletterSchema.safeParse(body)

    if (!validationResult.success) {
      return NextResponse.json(
        { 
          error: 'Validation failed',
          details: validationResult.error.flatten().fieldErrors,
        },
        { status: 400 }
      )
    }

    const data = validationResult.data

    // Subscribe to newsletter
    const subscriptionResult = await subscribeToNewsletter(data)

    // Log subscription for tracking
    console.log('✅ Newsletter subscription:', {
      email: data.email,
      name: data.name,
      timestamp: new Date().toISOString(),
      provider: subscriptionResult.provider,
      alreadySubscribed: subscriptionResult.alreadySubscribed,
    })

    if (subscriptionResult.alreadySubscribed) {
      return NextResponse.json({
        success: true,
        message: 'You are already subscribed to our newsletter!',
      })
    }

    return NextResponse.json({
      success: true,
      message: 'Successfully subscribed to newsletter! Check your email for confirmation.',
    })
  } catch (error) {
    console.error('Newsletter API error:', error)
    
    return NextResponse.json(
      { 
        error: 'An error occurred while subscribing. Please try again later.',
        details: process.env.NODE_ENV === 'development' ? String(error) : undefined,
      },
      { status: 500 }
    )
  }
}

// OPTIONS handler for CORS
export async function OPTIONS() {
  return NextResponse.json({}, { status: 200 })
}

