// GET /api/hail/engagements/[id]/governance  — list governance matrix rules
// PUT /api/hail/engagements/[id]/governance  — replace the matrix (each row validated)
//
// PUT body: { rules: [ { action_type, risk, authority, role_slug?, data_class?,
//   reviewer_role?, approval_required?, evidence_required? } ] }. Rejects the
// whole edit (422) if any rule is invalid. Practitioner-gated.

import { getEngagement } from '../../../../../../lib/hail/engagements.js';
import { listGovernanceRules, replaceGovernanceRules } from '../../../../../../lib/hail/blueprint.js';
import { requirePractitioner, errorResponse } from '../../../guard.js';

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

export async function GET(req, { params }) {
  const { id } = await params;
  try {
    await requirePractitioner(req);
    if (!getEngagement(id)) return Response.json({ error: 'engagement_not_found' }, { status: 404 });
    return Response.json({ rules: listGovernanceRules(id) });
  } catch (err) {
    return errorResponse(err);
  }
}

export async function PUT(req, { params }) {
  const { id } = await params;
  let body;
  try { body = await req.json(); } catch { return Response.json({ ok: false, error: 'invalid_json' }, { status: 400 }); }
  try {
    await requirePractitioner(req);
    if (!getEngagement(id)) return Response.json({ error: 'engagement_not_found' }, { status: 404 });
    const rules = replaceGovernanceRules(id, body?.rules);
    return Response.json({ ok: true, rules });
  } catch (err) {
    if (err?.code === 'blueprint_invalid') return Response.json({ ok: false, error: 'governance_invalid', errors: err.errors }, { status: 422 });
    return errorResponse(err);
  }
}
