import type { Metadata } from 'next'

import { PermissionGate } from '@/components/console/permission-gate'
import { ScenarioRunner, type ScenarioView } from '@/components/console/scenario-runner'
import { DemoDataBadge, PageHeader } from '@/components/ui/display'
import { getCurrentUser } from '@/lib/auth/current-user'
import { prisma } from '@/lib/db'
import { getI18n } from '@/lib/i18n/server'

export const metadata: Metadata = { title: 'What-if scenarios' }
export const dynamic = 'force-dynamic'

export default async function ScenariosPage() {
  const user = await getCurrentUser()
  const { t } = await getI18n()

  if (!user?.permissions.has('scenarios.read')) return <PermissionGate />

  const [scenarios, regions] = await Promise.all([
    prisma.scenario.findMany({
      orderBy: [{ isBuiltIn: 'desc' }, { name: 'asc' }],
      include: { targetAsset: { select: { code: true } } },
    }),
    prisma.region.findMany({ select: { code: true, name: true, nameAr: true }, orderBy: { code: 'asc' } }),
  ])

  const views: ScenarioView[] = scenarios.map((scenario) => ({
    id: scenario.id,
    key: scenario.key,
    name: scenario.name,
    nameAr: scenario.nameAr,
    description: scenario.description,
    descriptionAr: scenario.descriptionAr,
    category: scenario.category,
    loadDeltaPct: scenario.loadDeltaPct,
    solarDeltaPct: scenario.solarDeltaPct,
    windDeltaPct: scenario.windDeltaPct,
    tempDeltaC: scenario.tempDeltaC,
    assetOutage: scenario.assetOutage,
    lineOutage: scenario.lineOutage,
    batteryOutage: scenario.batteryOutage,
    evSurgeMw: scenario.evSurgeMw,
    industrialMw: scenario.industrialMw,
    durationMin: scenario.durationMin,
    targetRegion: scenario.targetRegion,
    targetAssetCode: scenario.targetAsset?.code ?? null,
  }))

  return (
    <>
      <PageHeader
        title={t('scenarios.title')}
        subtitle={t('scenarios.subtitle')}
        badge={<DemoDataBadge label={t('common.simulated')} title={t('common.simulatedTooltip')} />}
      />
      <ScenarioRunner
        scenarios={views}
        regions={regions}
        canRun={user.permissions.has('simulations.run')}
        canCreate={user.permissions.has('scenarios.create')}
      />
    </>
  )
}
