import { NextRequest, NextResponse } from 'next/server'
import { requireStaffPermission } from '@/lib/auth-helpers'
import { emailService } from '@/lib/services/email-service'

/**
 * POST /api/v1/admin/settings/email/test
 * Test SMTP connection and optionally send a test email
 */
export async function POST(request: NextRequest) {
  try {
    await requireStaffPermission('settings:edit')
  } catch (err) {
    const error = err as { status?: number; message?: string }
    return NextResponse.json(
      { error: error.message || 'Unauthorized' },
      { status: error.status || 401 }
    )
  }

  try {
    const body = await request.json().catch(() => ({}))
    const { testEmail } = body as { testEmail?: string }

    // First, test the connection
    const connectionResult = await emailService.testConnection()
    if (!connectionResult.success) {
      return NextResponse.json(
        {
          success: false,
          error: connectionResult.error,
          connectionTest: false,
        },
        { status: 400 }
      )
    }

    // If a test email address is provided, send a test email
    if (testEmail) {
      const sendResult = await emailService.sendTestEmail(testEmail)
      return NextResponse.json({
        success: sendResult.success,
        connectionTest: true,
        emailSent: sendResult.success,
        error: sendResult.error,
        messageId: sendResult.messageId,
      })
    }

    // Just connection test
    return NextResponse.json({
      success: true,
      connectionTest: true,
      emailSent: false,
    })
  } catch (err) {
    console.error('Email test error:', err)
    return NextResponse.json(
      {
        success: false,
        error: err instanceof Error ? err.message : 'Failed to test email',
      },
      { status: 500 }
    )
  }
}
