import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/db'
import { verifyAdminAuth } from '@/lib/admin-auth'
import { mailgunService } from '@/lib/mailgun'

export const runtime = 'nodejs'

export async function GET(request: NextRequest) {
  try {
    const adminUser = await verifyAdminAuth(request)
    if (!adminUser) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const settings = await prisma.mailgunSettings.findFirst({
      orderBy: { updatedAt: 'desc' },
      select: {
        id: true,
        domain: true,
        region: true,
        fromEmail: true,
        fromName: true,
        replyToEmail: true,
        isEnabled: true,
        testMode: true,
        webhookUrl: true,
        createdAt: true,
        updatedAt: true,
        // Don't return the API key for security
        apiKey: false
      }
    })

    return NextResponse.json({
      success: true,
      data: settings
    })
  } catch (error) {
    console.error('Error fetching Mailgun settings:', error)
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
  }
}

export async function POST(request: NextRequest) {
  try {
    const adminUser = await verifyAdminAuth(request)
    if (!adminUser) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const body = await request.json()
    const {
      apiKey,
      domain,
      region = 'US',
      fromEmail,
      fromName,
      replyToEmail,
      isEnabled = false,
      testMode = true,
      webhookUrl
    } = body

    // Validate required fields
    if (!apiKey || !domain || !fromEmail || !fromName) {
      return NextResponse.json({
        error: 'API key, domain, from email, and from name are required'
      }, { status: 400 })
    }

    // Validate email format
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    if (!emailRegex.test(fromEmail)) {
      return NextResponse.json({
        error: 'Invalid from email format'
      }, { status: 400 })
    }

    if (replyToEmail && !emailRegex.test(replyToEmail)) {
      return NextResponse.json({
        error: 'Invalid reply-to email format'
      }, { status: 400 })
    }

    // Disable existing settings
    await prisma.mailgunSettings.updateMany({
      data: { isEnabled: false }
    })

    // Create new settings
    const settings = await prisma.mailgunSettings.create({
      data: {
        apiKey,
        domain,
        region,
        fromEmail,
        fromName,
        replyToEmail,
        isEnabled,
        testMode,
        webhookUrl,
        updatedBy: adminUser.id
      }
    })

    // Clear service cache
    mailgunService.clearCache()

    return NextResponse.json({
      success: true,
      data: {
        id: settings.id,
        domain: settings.domain,
        region: settings.region,
        fromEmail: settings.fromEmail,
        fromName: settings.fromName,
        replyToEmail: settings.replyToEmail,
        isEnabled: settings.isEnabled,
        testMode: settings.testMode,
        webhookUrl: settings.webhookUrl,
        createdAt: settings.createdAt,
        updatedAt: settings.updatedAt
      }
    })
  } catch (error) {
    console.error('Error creating Mailgun settings:', error)
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
  }
}

export async function PUT(request: NextRequest) {
  try {
    const adminUser = await verifyAdminAuth(request)
    if (!adminUser) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const body = await request.json()
    const {
      id,
      apiKey,
      domain,
      region,
      fromEmail,
      fromName,
      replyToEmail,
      isEnabled,
      testMode,
      webhookUrl
    } = body

    if (!id) {
      return NextResponse.json({ error: 'Settings ID is required' }, { status: 400 })
    }

    // Validate required fields
    if (!domain || !fromEmail || !fromName) {
      return NextResponse.json({
        error: 'Domain, from email, and from name are required'
      }, { status: 400 })
    }

    // Validate email format
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    if (!emailRegex.test(fromEmail)) {
      return NextResponse.json({
        error: 'Invalid from email format'
      }, { status: 400 })
    }

    if (replyToEmail && !emailRegex.test(replyToEmail)) {
      return NextResponse.json({
        error: 'Invalid reply-to email format'
      }, { status: 400 })
    }

    // If enabling this setting, disable others
    if (isEnabled) {
      await prisma.mailgunSettings.updateMany({
        where: { id: { not: id } },
        data: { isEnabled: false }
      })
    }

    // Build update data
    const updateData: any = {
      domain,
      region,
      fromEmail,
      fromName,
      replyToEmail,
      isEnabled,
      testMode,
      webhookUrl,
      updatedBy: adminUser.id
    }

    // Only update API key if provided
    if (apiKey) {
      updateData.apiKey = apiKey
    }

    const settings = await prisma.mailgunSettings.update({
      where: { id },
      data: updateData
    })

    // Clear service cache
    mailgunService.clearCache()

    return NextResponse.json({
      success: true,
      data: {
        id: settings.id,
        domain: settings.domain,
        region: settings.region,
        fromEmail: settings.fromEmail,
        fromName: settings.fromName,
        replyToEmail: settings.replyToEmail,
        isEnabled: settings.isEnabled,
        testMode: settings.testMode,
        webhookUrl: settings.webhookUrl,
        createdAt: settings.createdAt,
        updatedAt: settings.updatedAt
      }
    })
  } catch (error) {
    console.error('Error updating Mailgun settings:', error)
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
  }
}