// POST /api/hail/setup-packages/[id]/apply  — promote an APPROVED setup package
// into live madarX OS configuration.
//
// 403 unless the package status is 'approved' (or 'partially_applied' to resume).
// Idempotent: re-runnable, only non-terminal items re-process. Returns the
// per-item apply ledger. Practitioner-gated.

import { applySetupPackage } from '../../../../../../lib/hail/setup-applier.js';
import { requirePractitioner, errorResponse } from '../../../guard.js';

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

export async function POST(req, { params }) {
  const { id } = await params;
  try {
    const session = await requirePractitioner(req);
    const result = applySetupPackage(id, { user_id: session.user_id || null });
    return Response.json({ ok: true, result }, { status: 201 });
  } catch (err) {
    if (err?.code === 'package_not_approved') {
      return Response.json({ ok: false, error: 'package_not_approved', message: err.message }, { status: 403 });
    }
    if (err?.code === 'not_found') {
      return Response.json({ ok: false, error: 'not_found', message: err.message }, { status: 404 });
    }
    return errorResponse(err);
  }
}
