import { NextResponse } from 'next/server'

/**
 * Server-side proxy for Mailpit API
 * Avoids CORS and mixed-content issues by fetching from server
 */

// Use internal Docker hostname when running in container
const getMailpitHost = (): string => {
  return process.env.BACKEND_URL ? 'mailpit' : 'localhost'
}

export async function GET() {
  const host = getMailpitHost()
  const mailpitUrl = `http://${host}:8025/api/v1/info`

  try {
    const response = await fetch(mailpitUrl, {
      method: 'GET',
      signal: AbortSignal.timeout(5000),
    })

    if (!response.ok) {
      return NextResponse.json(
        { error: 'Mailpit API error', status: response.status },
        { status: response.status }
      )
    }

    const data = await response.json()

    // Transform Mailpit response to our expected format
    return NextResponse.json({
      stats: {
        totalAccounts: 1,
        activeAccounts: 1,
        totalEmails: data.Messages || 0,
        unreadEmails: data.Unread || 0,
        totalTasks: 0,
        pendingTasks: 0,
        overdueTasks: 0,
        aiAnalyzedCount: 0,
        lastSyncTime: new Date().toISOString(),
      },
      accounts: [{
        id: 'mailpit-dev',
        email: 'dev@mailpit.local',
        displayName: 'Mailpit (Development)',
        imapHost: 'mailpit',
        imapPort: 1143,
        smtpHost: 'mailpit',
        smtpPort: 1025,
        status: 'active' as const,
        lastSync: new Date().toISOString(),
        emailCount: data.Messages || 0,
        unreadCount: data.Unread || 0,
        createdAt: new Date().toISOString(),
      }],
      syncStatus: {
        running: false,
        accountsInProgress: [],
        lastCompleted: new Date().toISOString(),
        errors: [],
      },
      mailpitInfo: {
        version: data.Version,
        databaseSize: data.DatabaseSize,
        uptime: data.RuntimeStats?.Uptime,
      }
    })
  } catch (error) {
    console.error('Failed to fetch from Mailpit:', error)
    return NextResponse.json(
      {
        error: 'Failed to connect to Mailpit',
        details: error instanceof Error ? error.message : 'Unknown error'
      },
      { status: 503 }
    )
  }
}
