import { getCase, transitionTo, createStageExecution } from '../../../../../../../lib/process/engine.js';
import { getStage, nextStageAfter, failureStageAfter } from '../../../../../../../lib/process/definitions.js';

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

// Admin force-transition. Records an explicit pass/fail execution and advances
// the case via the engine's normal transition path. transitionTo writes the
// process.stage.override audit event (reason field).
export async function POST(req, { params }) {
  const { id, stageId } = await params;
  const c = getCase(id);
  if (!c) return Response.json({ error: 'case_not_found' }, { status: 404 });
  const stage = getStage(stageId);
  if (!stage) return Response.json({ error: 'stage_not_found' }, { status: 404 });
  const body = await req.json().catch(() => ({}));
  const outcome = body.outcome === 'fail' ? 'fail' : 'pass';
  const reason = body.reason || `admin_override_${outcome}`;

  createStageExecution({ case_id: c.id, stage, status: outcome, outcome, output: { override: true, reason } });

  const next = outcome === 'pass' ? nextStageAfter(stage) : failureStageAfter(stage);
  const transition = next
    ? { next_stage: next }
    : { terminal_status: outcome === 'pass' ? 'complete' : 'rejected' };
  const updated = transitionTo({ case_id: c.id, from_stage_id: stage.id, reason, user_id: body.user_id || null, ...transition });
  return Response.json({ case: updated });
}
