import { submitIntake, getCase } from '../../../../../../../lib/process/engine.js';
import { getStage } from '../../../../../../../lib/process/definitions.js';
import { consumeShareToken } from '../../../../../../../lib/share-token.js';

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

// Submit an intake payload. Accepts either a session cookie (authenticated
// dashboard use) OR a `?token=` HMAC share-link token (anonymous client
// submission). The token is consumed atomically — replay returns 400.
//
// `stageId` in the URL path is the stage SLUG (matches the artifact's
// submit_endpoint built by the renderer).
export async function POST(req, { params }) {
  const { id, stageId } = await params;
  try {
    const url = new URL(req.url);
    const body = await req.json().catch(() => ({}));
    const token = url.searchParams.get('token') || body.token || null;
    const payload = body.payload || (body && typeof body === 'object' && !body.token ? body : {});

    if (token) {
      // Share-link path: consume the token first so a bad payload doesn't
      // burn a token (consumeShareToken throws on any failure; submitIntake
      // failure rolls forward — the token is already consumed and that's
      // intentional, single-use means single-use even on validation error).
      const claims = consumeShareToken({
        token,
        consumer_ip: req.headers.get('x-forwarded-for') || null,
      });
      if (claims.c !== id) {
        return Response.json({ error: 'share_token: case_mismatch' }, { status: 400 });
      }
      const c = getCase(id);
      const stage = c ? getStage(c.current_stage_id) : null;
      if (!c || !stage || (stage.slug !== stageId && stage.id !== stageId)) {
        return Response.json({ error: 'stage_mismatch' }, { status: 400 });
      }
      if (claims.s !== stage.id) {
        return Response.json({ error: 'share_token: stage_mismatch' }, { status: 400 });
      }
    }

    const c = submitIntake({
      case_id: id,
      payload,
      user_id: body.user_id || null,
    });
    return Response.json({ case: c, ok: true });
  } catch (err) {
    return Response.json({ error: err?.message || String(err), ok: false }, { status: 400 });
  }
}
