import { setToolEnabled } 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 PUT(req, { params }) {
  let body;
  try {
    body = await req.json();
  } catch {
    return new Response('Invalid JSON', { status: 400 });
  }
  if (typeof body.enabled !== 'boolean') {
    return new Response('enabled must be a boolean', { status: 400 });
  }
  try {
    const session = await requireSession(req);
    requireAdmin(session);
    const tool = setToolEnabled(params.name, body.enabled);
    return Response.json({ ok: true, tool });
  } catch (err) {
    if (err && typeof err === 'object' && err.status) {
      return Response.json({ error: err.error || 'unauthorized' }, { status: err.status });
    }
    return new Response(err.message, { status: 404 });
  }
}
