/**
 * GET  /api/tool-allowlists  — list all allowlist entries grouped by tool
 * POST /api/tool-allowlists  — add a new entry (admin only)
 */

import { listAll, addEntry } from '@/lib/tool-allowlists.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' };
  }
}

function catchAuth(err) {
  if (err && typeof err === 'object' && err.status) {
    return Response.json({ error: err.error || 'unauthorized' }, { status: err.status });
  }
  return null;
}

export async function GET(req) {
  try {
    await requireSession(req);
    return Response.json({ ok: true, allowlists: listAll() });
  } catch (err) {
    return catchAuth(err) ?? Response.json({ ok: false, error: err.message }, { status: 500 });
  }
}

export async function POST(req) {
  let body;
  try {
    body = await req.json();
  } catch {
    return new Response('Invalid JSON', { status: 400 });
  }

  const tool_name = String(body?.tool_name || '').trim();
  const scope_key = String(body?.scope_key || '').trim();
  const scope_value = String(body?.scope_value ?? '').trim();
  const label = body?.label ? String(body.label).trim() : undefined;

  if (!tool_name) return new Response('tool_name is required', { status: 400 });
  if (!scope_key) return new Response('scope_key is required', { status: 400 });
  if (!scope_value) return new Response('scope_value is required', { status: 400 });

  try {
    const session = await requireSession(req);
    requireAdmin(session);
    const entry = addEntry({ tool_name, scope_key, scope_value, label });
    return Response.json({ ok: true, entry }, { status: 201 });
  } catch (err) {
    const authResp = catchAuth(err);
    if (authResp) return authResp;
    const isDupe = /UNIQUE constraint failed/i.test(err.message);
    return Response.json(
      { ok: false, error: isDupe ? 'Entry already exists' : err.message },
      { status: isDupe ? 409 : 500 }
    );
  }
}
