// GET  /api/hail/engagements  — list HAIL engagements (practitioner only)
// POST /api/hail/engagements  — create an engagement (provisions project + lifecycle case)
//
// Creation enforces the named-accountable-human rule. Both reads and writes
// require a practitioner — engagement data is sensitive operating-model content.

import { listEngagements, createEngagement } from '../../../../lib/hail/engagements.js';
import { requirePractitioner, errorResponse } from '../guard.js';

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

export async function GET(req) {
  try {
    await requirePractitioner(req);
    const { searchParams } = new URL(req.url);
    const status = searchParams.get('status') || null;
    return Response.json({ engagements: listEngagements({ status }) });
  } catch (err) {
    return errorResponse(err);
  }
}

export async function POST(req) {
  let body;
  try {
    body = await req.json();
  } catch {
    return Response.json({ ok: false, error: 'invalid_json' }, { status: 400 });
  }
  try {
    const session = await requirePractitioner(req);
    const engagement = createEngagement({
      principal_name: body?.principal_name,
      institution_type: body?.institution_type || null,
      accountable_human: body?.accountable_human,
      confidentiality_posture: body?.confidentiality_posture || undefined,
      org_id: session.org_id || null,
      created_by_user_id: session.user_id || null,
    });
    return Response.json({ ok: true, engagement }, { status: 201 });
  } catch (err) {
    if (err?.code === 'HAIL_NO_ACCOUNTABLE_HUMAN') {
      return Response.json({ ok: false, error: 'accountable_human_required', message: err.message }, { status: 422 });
    }
    return errorResponse(err);
  }
}
