import {
  getCase,
  listExecutions,
  listStages,
  cancelCase,
} from '../../../../lib/process/engine.js';
import { 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';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

export async function GET(_req, { params }) {
  const { id } = await params;
  const c = getCase(id);
  if (!c) return Response.json({ error: 'case_not_found' }, { status: 404 });
  const definition = getDefinition(c.definition_id);
  const stages = listStages(c.definition_id);
  const executions = listExecutions(c.id);
  const approvals = executions
    .filter((e) => e.approval_request_id)
    .map((e) => getApprovalRequest(e.approval_request_id))
    .filter(Boolean);
  const artifacts = listArtifactsByIds(aggregateCaseArtifacts(c, executions));
  return Response.json({ case: c, definition, stages, executions, approvals, artifacts });
}

export async function PATCH(req, { params }) {
  const { id } = await params;
  try {
    const body = await req.json().catch(() => ({}));
    if (body.status === 'cancelled') {
      const c = cancelCase({ case_id: id, reason: body.reason || null });
      return Response.json({ case: c });
    }
    return Response.json({ error: 'unsupported_patch' }, { status: 400 });
  } catch (err) {
    return Response.json({ error: err?.message || String(err) }, { status: 400 });
  }
}
