/**
 * Path B kill switch.
 *
 *   GET    /api/admin/path-b           → returns { disabled: boolean }
 *   POST   /api/admin/path-b/disable   → sets disabled=true (handled below)
 *   POST   /api/admin/path-b/enable    → sets disabled=false
 *
 * Auth: Bearer NEXTAUTH_SECRET (ops bootstrap), same pattern as the
 * /api/admin/backfill-isolation endpoint. We deliberately do NOT accept
 * workspace API keys here — flipping a global feature flag is a
 * platform-level action.
 *
 * When `path_b_disabled = true`:
 *   - shell.exec, fs.*, devcontainer.* return 503 from /api/mcp
 *   - the chat system prompt falls back to Path A (Gitea-write) guidance
 *   - existing dev containers keep running until they idle-suspend
 *     (no force-kill — graceful drain)
 *
 * Reverting is a single POST. Cache TTL is 10s, so the flip propagates
 * to every Vibn pod within ~10s of the SQL update.
 */

import { NextResponse } from 'next/server';
import { getFlag, setFlag } from '@/lib/feature-flags';

function authorized(request: Request): boolean {
  const auth = request.headers.get('authorization') ?? '';
  const bearer = auth.toLowerCase().startsWith('bearer ') ? auth.slice(7).trim() : '';
  return Boolean(bearer && process.env.NEXTAUTH_SECRET && bearer === process.env.NEXTAUTH_SECRET);
}

export async function GET(request: Request) {
  if (!authorized(request)) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }
  const disabled = await getFlag<boolean>('path_b_disabled', false);
  return NextResponse.json({ disabled });
}
