import { getCase } from '@/lib/process/engine.js';
import { getStage } from '@/lib/process/definitions.js';
import { getSettings } from '@/lib/process/definition-settings.js';
import { mintShareToken, listConsumptions, SHARE_TOKEN_DEFAULT_EXPIRY_DAYS } from '@/lib/share-token.js';

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

// POST /api/processes/<case_id>/share-link
// Body: { user_id?, expires_in_days? }
//
// Mints a single-use HMAC share token bound to the case's CURRENT intake
// stage. Requires the (definition, project) settings to have
// share_link_enabled=1; otherwise 403. The raw token is returned ONCE in
// the response — the server stores only its SHA-256 hash thereafter.
export async function POST(req, { params }) {
  const { id } = await params;
  try {
    const body = await req.json().catch(() => ({}));
    const c = getCase(id);
    if (!c) return Response.json({ error: 'case_not_found' }, { status: 404 });
    if (c.status !== 'intake') {
      return Response.json({ error: `share-link unavailable — case is ${c.status}` }, { status: 400 });
    }
    const stage = getStage(c.current_stage_id);
    if (!stage || stage.kind !== 'intake_form') {
      return Response.json({ error: 'share-link only available on intake_form stage' }, { status: 400 });
    }
    const settings = getSettings({ definition_id: c.definition_id, project_id: c.project_id });
    if (!settings?.share_link_enabled) {
      return Response.json({ error: 'share_link_disabled' }, { status: 403 });
    }
    const expiryDays = Number(body.expires_in_days || settings.share_link_default_expiry_days || SHARE_TOKEN_DEFAULT_EXPIRY_DAYS);
    const expires_at_iso = new Date(Date.now() + expiryDays * 86400_000).toISOString();
    const { token, expires_at } = mintShareToken({
      case_id: id,
      stage_id: stage.id,
      expires_at_iso,
      minted_by_user_id: body.user_id || null,
    });
    const proto = req.headers.get('x-forwarded-proto') || 'http';
    const host = req.headers.get('host') || '127.0.0.1:8787';
    const link = `${proto}://${host}/workflows/share/${id}?token=${encodeURIComponent(token)}`;
    // share_link_consumptions row created by mintShareToken IS the mint
    // audit trail (id, case_id, stage_id, token_hash, expires_at,
    // minted_by_user_id, minted_at, consumed_at, consumer_ip, revoked_at).
    return Response.json({ token, link, expires_at }, { status: 201 });
  } catch (err) {
    return Response.json({ error: err?.message || String(err) }, { status: 400 });
  }
}

export async function GET(_req, { params }) {
  const { id } = await params;
  const links = listConsumptions({ case_id: id });
  return Response.json({ links });
}
