import type { Metadata } from 'next'

import { AuditTable, type AuditRow } from '@/components/console/audit-table'
import { PermissionGate } from '@/components/console/permission-gate'
import { PageHeader, Panel, PanelBody, StatCard } from '@/components/ui/display'
import { getCurrentUser } from '@/lib/auth/current-user'
import { prisma } from '@/lib/db'
import { getI18n } from '@/lib/i18n/server'
import { formatNumber } from '@/lib/i18n/translate'

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

export default async function AuditPage() {
  const user = await getCurrentUser()
  const { t, locale } = await getI18n()

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

  // The audit log is append-only and grows without limit, so the page reads a bounded
  // window rather than the whole table (§50).
  const [entries, total, denied, distinctActions] = await Promise.all([
    prisma.auditLog.findMany({ orderBy: { ts: 'desc' }, take: 300 }),
    prisma.auditLog.count(),
    prisma.auditLog.count({ where: { status: 'denied' } }),
    prisma.auditLog.findMany({ select: { action: true }, distinct: ['action'], take: 60 }),
  ])

  const rows: AuditRow[] = entries.map((entry) => ({
    id: entry.id,
    ts: entry.ts.getTime(),
    userEmail: entry.userEmail,
    userRole: entry.userRole,
    action: entry.action,
    entity: entry.entity,
    entityId: entry.entityId,
    ip: entry.ip,
    status: entry.status,
    detail: entry.detail,
    beforeJson: entry.beforeJson,
    afterJson: entry.afterJson,
  }))

  return (
    <>
      <PageHeader title={t('audit.title')} subtitle={t('audit.subtitle')} />

      <div className="grid gap-3 sm:grid-cols-3">
        <StatCard label={t('audit.title')} value={formatNumber(locale, total)} />
        <StatCard
          label={t('common.permissionDenied')}
          value={formatNumber(locale, denied)}
          state={denied > 0 ? 'watch' : 'normal'}
        />
        <StatCard
          label={t('audit.columns.action')}
          value={formatNumber(locale, distinctActions.length)}
        />
      </div>

      <Panel className="mt-6">
        <PanelBody>
          <AuditTable rows={rows} actions={distinctActions.map((entry) => entry.action)} />
        </PanelBody>
      </Panel>
    </>
  )
}
