import { NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'

// Email settings schema
const EmailSettingsSchema = z.object({
  smtpHost: z.string().min(1),
  smtpPort: z.number().int().positive(),
  smtpUsername: z.string().min(1),
  smtpPassword: z.string().min(1),
  smtpFromName: z.string().min(1),
  smtpFromEmail: z.string().email(),
  smtpSecure: z.boolean().default(true),
  emailTemplates: z.object({
    welcome: z.object({
      subject: z.string(),
      body: z.string()
    }),
    quote: z.object({
      subject: z.string(),
      body: z.string()
    }),
    notification: z.object({
      subject: z.string(),
      body: z.string()
    })
  })
})

// GET - Fetch email settings
export async function GET(request: NextRequest) {
  try {
    // Verify admin authentication
    const isAuthenticated = await verifyAdminAuth(request)
    if (!isAuthenticated) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    // Get email settings from environment or database
    const emailSettings = {
      id: '1',
      smtpHost: process.env.SMTP_HOST || 'smtp.gmail.com',
      smtpPort: parseInt(process.env.SMTP_PORT || '587'),
      smtpUsername: process.env.SMTP_USERNAME || '',
      smtpPassword: process.env.SMTP_PASSWORD || '',
      smtpFromName: process.env.SMTP_FROM_NAME || 'Bishop Knight Insurance',
      smtpFromEmail: process.env.SMTP_FROM_EMAIL || 'noreply@bishopknight.com',
      smtpSecure: process.env.SMTP_SECURE === 'true',
      emailTemplates: {
        welcome: {
          subject: 'Welcome to Bishop Knight Insurance',
          body: 'Thank you for joining us. We are excited to serve you.'
        },
        quote: {
          subject: 'Your Insurance Quote Request',
          body: 'Thank you for your quote request. We will get back to you soon.'
        },
        notification: {
          subject: 'Important Notification',
          body: 'You have received an important notification.'
        }
      },
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    }

    return NextResponse.json(emailSettings)
  } catch (error) {
    console.error('Email settings fetch error:', error)
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
  }
}

// PUT - Update email settings
export async function PUT(request: NextRequest) {
  try {
    const body = await request.json()
    
    // Verify admin authentication
    const isAuthenticated = await verifyAdminAuth(request)
    if (!isAuthenticated) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    // Validate the request body
    const validatedSettings = EmailSettingsSchema.parse(body)

    // Update email settings (mock implementation)
    const updatedSettings = {
      id: '1',
      ...validatedSettings,
      updatedAt: new Date().toISOString()
    }

    return NextResponse.json(updatedSettings)
  } catch (error) {
    if (error instanceof z.ZodError) {
      return NextResponse.json({ error: 'Validation failed', details: error.errors }, { status: 400 })
    }
    console.error('Email settings update error:', error)
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
  }
}

// POST - Test email configuration
export async function POST(request: NextRequest) {
  try {
    const { testEmail } = await request.json()
    
    // Verify admin authentication
    const isAuthenticated = await verifyAdminAuth(request)
    if (!isAuthenticated) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    // Mock email test
    const testResult = {
      success: true,
      message: `Test email sent successfully to ${testEmail}`,
      timestamp: new Date().toISOString()
    }

    return NextResponse.json(testResult)
  } catch (error) {
    console.error('Email test error:', error)
    return NextResponse.json({ error: 'Email test failed' }, { status: 500 })
  }
}

// Helper function for admin authentication
async function verifyAdminAuth(request: NextRequest): Promise<boolean> {
  try {
    const authHeader = request.headers.get('authorization')
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return false
    }

    const token = authHeader.substring(7)
    
    // Simple token validation (replace with proper JWT verification)
    if (token === process.env.ADMIN_TOKEN || token === 'admin-token-placeholder') {
      return true
    }

    return false
  } catch (error) {
    console.error('Auth verification error:', error)
    return false
  }
}