import { executeRegistryTool } from '@/lib/tools/registry.js';
import { requireSession } from '@/lib/auth.js';
import { appendAudit } from '@/lib/runtime.js';

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

function requireAdmin(session) {
  if (session.role !== 'admin' && session.role !== 'owner') {
    throw { status: 403, error: 'forbidden' };
  }
}

export async function POST(req) {
  let body;
  try {
    body = await req.json().catch(() => ({}));
  } catch {
    body = {};
  }
  let session;
  try {
    session = await requireSession(req);
    requireAdmin(session);
  } catch (err) {
    if (err && typeof err === 'object' && err.status) {
      return Response.json({ error: err.error || 'unauthorized' }, { status: err.status });
    }
    throw err;
  }

  // Always goes through executeRegistryTool so irreversible_external gate +
  // strict-mode gate + rate-limit gate all fire. The user must supply an
  // approval_id on the second call to actually proceed.
  const result = await executeRegistryTool('printing_press_install',
    { approval_id: body?.approval_id || null },
    { user_id: session.user_id, acting_on_behalf_of_user_id: session.user_id }
  );

  appendAudit({
    type: result?.ok ? 'printing_press.install.completed' : 'printing_press.install.gated',
    summary: result?.ok ? 'Printing Press starter pack installed' : `Printing Press install gated: ${result?.status}`,
    status: result?.ok ? 'success' : (result?.status || 'gated'),
    meta: { actor: session.user_id || 'owner', status: result?.status },
  });

  return Response.json(result);
}
