import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
import { requireUser } from '@/lib/auth/dal';
import { isAdmin } from '@/lib/auth/roles';
import { canEditReport, findReportForUser, toReportData } from '@/lib/reports/access';
import { ReportView } from '@/components/report/ReportView';
import { getMessages } from '@/i18n/server';

export async function generateMetadata(): Promise<Metadata> {
  return { title: (await getMessages()).account.reportMeta, robots: { index: false } };
}

export default async function ReportPage({ params }: PageProps<'/laporan/[id]'>) {
  const { id } = await params;
  const user = await requireUser(`/laporan/${id}`);
  const row = await findReportForUser(id, user);
  if (!row) notFound();

  const report = toReportData(row);
  // Staff opening a participant's report go back to that session; everyone else to their reports.
  const fromSession = report.event && row.ownerId !== user.id && isAdmin(user.role);

  return (
    <ReportView
      report={report}
      mode={{
        kind: 'member',
        backHref: fromSession ? `/admin/sesi/${report.event!.id}` : '/akun/laporan',
        backLabel: fromSession ? report.event!.name : (await getMessages()).account.eyebrow,
        canEdit: canEditReport(user, row),
      }}
    />
  );
}
