import type { Metadata } from 'next'

import { PermissionGate } from '@/components/console/permission-gate'
import { SensorConsole } from '@/components/sensors/sensor-console'
import { DemoDataBadge, PageHeader } from '@/components/ui/display'
import { getCurrentUser } from '@/lib/auth/current-user'
import { getI18n } from '@/lib/i18n/server'
import { prisma } from '@/lib/db'

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

/**
 * The sensor inspector and provenance graph (5.0 §4–§5).
 *
 * Only assets that actually carry instruments are offered. Listing every asset and letting
 * most of them answer "no sensors" would make an empty inventory look like a broken screen.
 */
export default async function SensorsPage() {
  const user = await getCurrentUser()
  const { t } = await getI18n()
  if (!user?.permissions.has('twin.read')) return <PermissionGate />

  const rows = await prisma.asset.findMany({
    where: { sensors: { some: {} } },
    select: { code: true, name: true, nameAr: true },
    orderBy: { code: 'asc' },
    take: 200,
  })

  return (
    <>
      <PageHeader
        title={t('sensor.inspector')}
        subtitle={t('sensor.subtitle')}
        badge={<DemoDataBadge label={t('common.simulated')} title={t('sensor.dataAnomalyNote')} />}
      />
      <SensorConsole
        assets={rows}
        initialAsset={rows[0]?.code ?? ''}
        canSimulate={user.permissions.has('twin.simulate')}
      />
    </>
  )
}
