import { setConfig } from '@/lib/config.js';
import {
  TRUST_MODE_CONFIG_KEY,
  TRUST_MODE_DEFAULT,
  TRUST_MODE_VALUES,
  getMainAgentTrustMode,
} from '@/lib/tools/registry.js';
import { appendAudit } from '@/lib/runtime.js';
import { requireSession } from '@/lib/auth.js';

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

function snapshot() {
  const mode = getMainAgentTrustMode();
  return {
    mode,
    default: TRUST_MODE_DEFAULT,
    is_trusted: mode === 'auto',
  };
}

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

export async function GET(req) {
  try {
    await requireSession(req);
    return Response.json({ ok: true, ...snapshot() });
  } catch (err) {
    if (err && typeof err === 'object' && err.status) {
      return Response.json({ error: err.error || 'unauthorized' }, { status: err.status });
    }
    throw err;
  }
}

export async function PATCH(req) {
  let body;
  try {
    body = await req.json();
  } catch {
    return new Response('Invalid JSON', { status: 400 });
  }
  const next = String(body?.mode || '').trim();
  if (!TRUST_MODE_VALUES.has(next)) {
    return Response.json({
      ok: false,
      error: `mode must be one of: ${[...TRUST_MODE_VALUES].join(', ')}`,
    }, { status: 400 });
  }
  try {
    const 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 previous = getMainAgentTrustMode();
  if (next === 'auto' && !body?.confirm) {
    return Response.json({
      ok: false,
      error: 'Switching to trust mode requires confirm:true in the body',
      previous,
    }, { status: 400 });
  }
  setConfig(TRUST_MODE_CONFIG_KEY, next);
  appendAudit({
    type: next === 'auto' ? 'settings.trust_mode.enabled' : 'settings.trust_mode.disabled',
    summary: `Main agent trust mode set to ${next}`,
    status: next,
    meta: { previous, next, actor: 'owner' },
  });
  return Response.json({ ok: true, previous, ...snapshot() });
}
