import { NextRequest, NextResponse } from 'next/server';
import { getLLMGateStatus, updateLLMGateConfig } from '@/lib/gfs/engine/llm-gate';

export const dynamic = 'force-dynamic';

/**
 * GET /api/gfs/llm-gate
 * Returns current LLM gate status and configuration.
 */
export async function GET() {
  try {
    const status = await getLLMGateStatus();
    return NextResponse.json(status);
  } catch (error) {
    console.error('LLM Gate GET error:', error);
    return NextResponse.json({ error: 'Failed to fetch LLM gate status' }, { status: 500 });
  }
}

/**
 * PUT /api/gfs/llm-gate
 * Update LLM gate configuration.
 * Body: { globalEnabled?: boolean, scopes?: Record<string, boolean>, reason?: string }
 */
export async function PUT(request: NextRequest) {
  try {
    const body = await request.json();
    const { globalEnabled, scopes, reason } = body;

    const updates: Record<string, unknown> = {};
    if (typeof globalEnabled === 'boolean') updates.globalEnabled = globalEnabled;
    if (scopes && typeof scopes === 'object') updates.scopes = scopes;
    if (reason) updates.lastModifiedReason = reason;

    const newConfig = await updateLLMGateConfig(updates as any, 'operator');
    const status = await getLLMGateStatus();

    return NextResponse.json({
      success: true,
      ...status,
    });
  } catch (error) {
    console.error('LLM Gate PUT error:', error);
    return NextResponse.json({ error: 'Failed to update LLM gate' }, { status: 500 });
  }
}
