/**
 * DELETE /api/tool-allowlists/[id]  — remove an allowlist entry by id (admin only)
 */

import { removeEntry } 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' };
  }
}

export async function DELETE(req, { params }) {
  const { id } = await params;

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

  try {
    const session = await requireSession(req);
    requireAdmin(session);
    removeEntry(id);
    return Response.json({ ok: true, id });
  } catch (err) {
    if (err && typeof err === 'object' && err.status) {
      return Response.json({ error: err.error || 'unauthorized' }, { status: err.status });
    }
    const notFound = /not found/i.test(err.message);
    return Response.json(
      { ok: false, error: err.message },
      { status: notFound ? 404 : 500 }
    );
  }
}
