import { getCase, enqueueStageExecution } from '../../../../../../../lib/process/engine.js';
import { getStage } from '../../../../../../../lib/process/definitions.js';
import { getDb } from '../../../../../../../lib/db.js';

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

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 });
  // Increment attempt counter from the latest execution for this stage.
  const db = getDb();
  const latest = db
    .prepare('SELECT MAX(attempt) AS attempt FROM process_stage_executions WHERE case_id = ? AND stage_id = ?')
    .get(c.id, stage.id);
  const attempt = Number(latest?.attempt || 0) + 1;
  const { execution_id, heartbeat_task_id } = enqueueStageExecution({ case_id: c.id, stage, attempt });
  return Response.json({ execution_id, heartbeat_task_id });
}
