import { NextResponse } from 'next/server'
import { prisma } from '@/lib/db'
import { requireAdmin } from '@/lib/auth'

// Simple in-memory cache stats (in production, use Redis)
const cacheStats = {
  hits: 0,
  misses: 0,
  size: 0
}

const startTime = Date.now()

export async function GET() {
  try {
    const adminCheck = await requireAdmin()
    if (adminCheck) return adminCheck

    // Check database health
    const dbStart = Date.now()
    let dbStatus: 'healthy' | 'degraded' | 'error' = 'healthy'
    let dbLatency = 0
    
    try {
      await prisma.$queryRaw`SELECT 1`
      dbLatency = Date.now() - dbStart
      if (dbLatency > 500) dbStatus = 'degraded'
    } catch {
      dbStatus = 'error'
      dbLatency = -1
    }

    // Get last backup
    const lastBackup = await prisma.updateHistory.findFirst({
      where: { backupPath: { not: null } },
      orderBy: { appliedAt: 'desc' },
      select: { appliedAt: true }
    })

    // Simulated storage info (in production, use actual disk stats)
    const storage = {
      used: 256 * 1024 * 1024, // 256MB
      total: 10 * 1024 * 1024 * 1024, // 10GB
      percentage: 2.5
    }

    // Calculate uptime
    const uptime = Math.floor((Date.now() - startTime) / 1000)

    return NextResponse.json({
      database: {
        status: dbStatus,
        latency: dbLatency,
        connections: 5 // Simulated
      },
      storage,
      cache: cacheStats,
      uptime,
      lastBackup: lastBackup?.appliedAt || null,
      pendingMigrations: 0
    })
  } catch (error) {
    console.error('Failed to fetch system status:', error)
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
  }
}
