import type { Metadata } from 'next'

import { PermissionGate } from '@/components/console/permission-gate'
import { DiscoveryLab } from '@/components/intelligence/discovery-lab'
import { DemoDataBadge, PageHeader } from '@/components/ui/display'
import { getCurrentUser } from '@/lib/auth/current-user'
import { REGIONS } from '@/lib/data/regions'
import { getI18n } from '@/lib/i18n/server'
import { listDiscoveries, listDiscoveryRuns } from '@/lib/services/discovery-service'

export const metadata: Metadata = { title: 'Scenario Discovery' }
export const dynamic = 'force-dynamic'

/**
 * The Scenario Discovery Lab (§19).
 *
 * Every other search in the platform starts from a question a person asked. This one
 * starts from the observation that people ask about the failures they already imagine.
 */
export default async function DiscoveryPage() {
  const user = await getCurrentUser()
  const { t } = await getI18n()
  if (!user?.permissions.has('discovery.read')) return <PermissionGate />

  const [discoveries, runs] = await Promise.all([
    listDiscoveries({ limit: 12 }),
    listDiscoveryRuns(8),
  ])

  return (
    <>
      <PageHeader
        title={t('discovery.title')}
        subtitle={t('discovery.subtitle')}
        badge={<DemoDataBadge label={t('common.simulated')} title={t('common.simulatedTooltip')} />}
      />

      <DiscoveryLab
        initialDiscoveries={discoveries}
        initialRuns={runs.map((run) => ({ ...run, createdAt: run.createdAt.getTime() }))}
        regions={REGIONS.map((region) => ({
          code: region.code,
          name: region.name,
          nameAr: region.nameAr,
        }))}
        canRun={user.permissions.has('discovery.run')}
      />
    </>
  )
}
