import { NextRequest } from 'next/server';

const BACKEND_BASE = process.env.BACKEND_INTERNAL_URL || process.env.NEXT_PUBLIC_BACKEND_URL;

// 聚合新后端的配置，提供给旧前端调用点一个稳定入口
export async function GET() {
  if (!BACKEND_BASE) {
    return new Response('BACKEND_INTERNAL_URL/NEXT_PUBLIC_BACKEND_URL 未配置', { status: 500 });
  }
  try {
    const [providersResp, modulesResp] = await Promise.all([
      fetch(`${BACKEND_BASE}/configs/llm_providers`, { cache: 'no-store' }),
      fetch(`${BACKEND_BASE}/configs/analysis_modules`, { cache: 'no-store' }),
    ]);
    const providersText = await providersResp.text();
    const modulesText = await modulesResp.text();
    let providers: unknown = {};
    let modules: unknown = {};
    try { providers = providersText ? JSON.parse(providersText) : {}; } catch { providers = {}; }
    try { modules = modulesText ? JSON.parse(modulesText) : {}; } catch { modules = {}; }
    return Response.json({
      llm_providers: providers,
      analysis_modules: modules,
    });
  } catch (e: any) {
    return new Response(e?.message || 'Failed to load config', { status: 502 });
  }
}

// 允许前端一次性提交部分配置；根据键路由到新后端
export async function PUT(req: NextRequest) {
  if (!BACKEND_BASE) {
    return new Response('BACKEND_INTERNAL_URL/NEXT_PUBLIC_BACKEND_URL 未配置', { status: 500 });
  }
  try {
    const incoming = await req.json().catch(() => ({}));
    const tasks: Promise<Response>[] = [];
    if (incoming.llm_providers) {
      tasks.push(fetch(`${BACKEND_BASE}/configs/llm_providers`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(incoming.llm_providers),
      }));
    }
    if (incoming.analysis_modules) {
      tasks.push(fetch(`${BACKEND_BASE}/configs/analysis_modules`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(incoming.analysis_modules),
      }));
    }
    const results = await Promise.all(tasks);
    const ok = results.every(r => r.ok);
    if (!ok) {
      const texts = await Promise.all(results.map(r => r.text().catch(() => '')));
      return new Response(JSON.stringify({ error: 'Partial update failed', details: texts }), {
        status: 502,
        headers: { 'Content-Type': 'application/json' },
      });
    }
    // 返回最新聚合
    const [providersResp, modulesResp] = await Promise.all([
      fetch(`${BACKEND_BASE}/configs/llm_providers`, { cache: 'no-store' }),
      fetch(`${BACKEND_BASE}/configs/analysis_modules`, { cache: 'no-store' }),
    ]);
    const providers = await providersResp.json().catch(() => ({}));
    const modules = await modulesResp.json().catch(() => ({}));
    return Response.json({
      llm_providers: providers,
      analysis_modules: modules,
    });
  } catch (e: any) {
    return new Response(e?.message || 'Failed to update config', { status: 502 });
  }
}
