// GET  /api/hail/engagements/[id]/quarterly  — list quarterly-review cases
// POST /api/hail/engagements/[id]/quarterly  — start a quarterly review
//
// Body (POST): { synthesize_delta?: boolean }. Starting a review requires the
// engagement to be in the Managed Layer. Optionally synthesizes a dry-run delta
// setup package (routes through the same approval → apply path). Practitioner-gated.

import { getEngagement } from '../../../../../../lib/hail/engagements.js';
import { startQuarterlyReview, listQuarterlyReviews, synthesizeReviewDelta } from '../../../../../../lib/hail/quarterly-review.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({ reviews: listQuarterlyReviews(id) });
  } catch (err) {
    return errorResponse(err);
  }
}

export async function POST(req, { params }) {
  const { id } = await params;
  let body = {};
  try { body = await req.json(); } catch { /* body optional */ }
  try {
    const session = await requirePractitioner(req);
    if (!getEngagement(id)) return Response.json({ error: 'engagement_not_found' }, { status: 404 });
    const caseRow = startQuarterlyReview(id, { created_by_user_id: session.user_id || null });
    let delta = null;
    if (body?.synthesize_delta) delta = synthesizeReviewDelta(id);
    return Response.json({ ok: true, case_id: caseRow.id, delta }, { status: 201 });
  } catch (err) {
    if (err?.code === 'not_managed_layer') return Response.json({ ok: false, error: 'not_managed_layer', message: err.message }, { status: 409 });
    if (err?.code === 'empty_delta') return Response.json({ ok: false, error: 'empty_delta', message: err.message }, { status: 422 });
    return errorResponse(err);
  }
}
