import { NextRequest, NextResponse } from 'next/server'
import { getPayload } from 'payload'
import config from '@payload-config'
import {
  checkRedis,
  checkPostgresql,
  checkPgBouncer,
  checkSmtp,
  checkOAuthTokens,
  checkCronJobs,
  checkQueues,
} from '@/lib/monitoring/monitoring-service'

function resolveSettled<T>(result: PromiseSettledResult<T>, fallback: T): T {
  if (result.status === 'fulfilled') {
    return result.value
  }
  return fallback
}

export async function GET(req: NextRequest): Promise<NextResponse> {
  try {
    const payload = await getPayload({ config })
    const { user } = await payload.auth({ headers: req.headers })

    if (!user || !(user as any).isSuperAdmin) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const [redis, postgresql, pgbouncer, smtp, oauth, cronJobs, queues] =
      await Promise.allSettled([
        checkRedis(),
        checkPostgresql(),
        checkPgBouncer(),
        checkSmtp(),
        checkOAuthTokens(),
        checkCronJobs(),
        checkQueues(),
      ])

    return NextResponse.json({
      data: {
        redis: resolveSettled(redis, {
          status: 'offline',
          memoryUsedMB: 0,
          connectedClients: 0,
          opsPerSec: 0,
        }),
        postgresql: resolveSettled(postgresql, {
          status: 'offline',
          connections: 0,
          maxConnections: 0,
          latencyMs: -1,
        }),
        pgbouncer: resolveSettled(pgbouncer, {
          status: 'offline',
          activeConnections: 0,
          waitingClients: 0,
          poolSize: 0,
        }),
        smtp: resolveSettled(smtp, {
          status: 'offline',
          lastCheck: new Date().toISOString(),
          responseTimeMs: -1,
        }),
        oauth: resolveSettled(oauth, {
          metaOAuth: { status: 'error', tokensTotal: 0, tokensExpiringSoon: 0, tokensExpired: 0 },
          youtubeOAuth: { status: 'error', tokensTotal: 0, tokensExpiringSoon: 0, tokensExpired: 0 },
        }),
        cronJobs: resolveSettled(cronJobs, {
          communitySync: { lastRun: '', status: 'unknown' },
          tokenRefresh: { lastRun: '', status: 'unknown' },
          youtubeSync: { lastRun: '', status: 'unknown' },
        }),
        queues: resolveSettled(queues, {}),
      },
      timestamp: new Date().toISOString(),
    })
  } catch (error: unknown) {
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Unknown error' },
      { status: 500 },
    )
  }
}

export const dynamic = 'force-dynamic'
