import { startCase, getCase } from '@/lib/process/engine.js';

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

// One-shot create — returns the case id, the intake artifact id (when the
// first stage is intake_form), and the dashboard URL to redirect to. The case
// always lands on the branded interactive intake artifact page.
//
// Body: { definition_slug, project_id, title?, created_by_user_id? }
export async function POST(req) {
  try {
    const body = await req.json();
    if (!body.definition_slug) return Response.json({ error: 'definition_slug required' }, { status: 400 });
    if (!body.project_id) return Response.json({ error: 'project_id required' }, { status: 400 });
    const c = startCase({
      definition_slug: body.definition_slug,
      project_id: body.project_id,
      title: body.title,
      created_by_user_id: body.created_by_user_id || null,
    });
    const fresh = getCase(c.id);
    const intake_artifact_id = fresh?.context?.intake_form_artifact_id || null;
    // Intake cases land on the branded interactive intake page; non-intake
    // first stages go straight to the case detail view.
    const redirect_url = fresh?.status === 'intake'
      ? `/workflows/new/${c.id}`
      : `/workflows/${c.id}`;
    return Response.json({
      case_id: c.id,
      intake_artifact_id,
      redirect_url,
      case: fresh,
    }, { status: 201 });
  } catch (err) {
    return Response.json({ error: err?.message || String(err) }, { status: 400 });
  }
}
