import { listInstalledClis, measureCliDiskUsage } from '@/lib/printing-press-registry.js';
import { executeRegistryTool } from '@/lib/tools/registry.js';
import { requireSession } from '@/lib/auth.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 GET(req) {
  try {
    await requireSession(req);
  } catch (err) {
    if (err && typeof err === 'object' && err.status) {
      return Response.json({ error: err.error || 'unauthorized' }, { status: err.status });
    }
    throw err;
  }
  const clis = listInstalledClis().map((cli) => ({
    ...cli,
    disk_usage: measureCliDiskUsage(cli.slug),
  }));
  return Response.json({ ok: true, clis });
}

export async function POST(req) {
  let body;
  try {
    body = await req.json();
  } catch {
    return new Response('Invalid JSON', { status: 400 });
  }
  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;
  }

  const slug = String(body?.slug || '').trim();
  if (!slug) return Response.json({ ok: false, error: 'slug is required' }, { status: 400 });

  const result = await executeRegistryTool('printing_press_generate', {
    slug,
    source: body?.source || 'starter-pack',
    source_url: body?.source_url || null,
    approval_id: body?.approval_id || null,
  }, { user_id: session.user_id, acting_on_behalf_of_user_id: session.user_id });

  return Response.json(result);
}
