import { prisma } from '@/lib/db'
import { apiRoute } from '@/lib/api/handler'
import { getGridSnapshot } from '@/lib/services/grid-service'
import { getPreventionScore } from '@/lib/services/prevention-service'

export const dynamic = 'force-dynamic'

/** The executive summary, as data. Every derived figure is a demo estimate (§20). */
export const GET = apiRoute({ permission: 'executive.read' }, async () => {
  const [snapshot, prevention, activePredictions, openAlerts] = await Promise.all([
    getGridSnapshot(),
    getPreventionScore(),
    prisma.prediction.count({ where: { status: 'active' } }),
    prisma.alert.count({ where: { status: { in: ['new', 'acknowledged', 'in_progress'] } } }),
  ])

  return {
    generatedAt: snapshot.ts,
    simulatedData: true,
    nationalHealth: snapshot.stabilityIndex,
    totalLoadMw: snapshot.totalLoadMw,
    reserveMarginPct: snapshot.reserveMarginPct,
    renewableSharePct: snapshot.renewableSharePct,
    criticalRisks: snapshot.assets.filter((asset) => asset.risk.score >= 75).length,
    predictedEvents: activePredictions,
    openAlerts,
    regionsAtRisk: snapshot.regions.filter((region) => region.peakRisk >= 55).length,
    prevention,
  }
})
