import Link from 'next/link';
import { notFound } from 'next/navigation';
import { AdminShell, StatusPill, EmptyState } from '../../components/admin/admin-page.jsx';
import { getCase, listExecutions } from '../../../lib/process/engine.js';
import { listStages, getDefinition } from '../../../lib/process/definitions.js';
import { getApprovalRequest } from '../../../lib/approvals.js';
import { aggregateCaseArtifacts } from '../../../lib/process/aggregate-case-artifacts.js';
import { listArtifactsByIds } from '../../../lib/process/case-artifacts-query.js';
import CaseDetailClient from './case-detail-client.jsx';

export const dynamic = 'force-dynamic';

export default async function CaseDetailPage({ params }) {
  const { caseId } = await params;
  const caseRow = getCase(caseId);
  if (!caseRow) return notFound();
  const definition = getDefinition(caseRow.definition_id);
  const stages = listStages(caseRow.definition_id);
  const executions = listExecutions(caseRow.id);
  const approvals = executions
    .filter((e) => e.approval_request_id)
    .map((e) => getApprovalRequest(e.approval_request_id))
    .filter(Boolean);
  const artifacts = listArtifactsByIds(aggregateCaseArtifacts(caseRow, executions));

  return (
    <AdminShell
      kicker={<Link href="/workflows">← Workflows</Link>}
      title={caseRow.title}
      description={`${definition?.name || caseRow.definition_slug} · case ${caseRow.id.slice(-8)}`}
    >
      <CaseDetailClient
        caseRow={caseRow}
        definition={definition}
        stages={stages}
        executions={executions}
        approvals={approvals}
        artifacts={artifacts}
      />
    </AdminShell>
  );
}
