import { NextRequest } from 'next/server';

const BACKEND_BASE = process.env.BACKEND_INTERNAL_URL || process.env.NEXT_PUBLIC_BACKEND_URL;
const FRONTEND_BASE = process.env.FRONTEND_INTERNAL_URL || 'http://localhost:3001';

export async function GET(
  req: NextRequest,
  context: { params: Promise<{ slug: string[] }> }
) {
  if (!BACKEND_BASE) {
    return new Response('BACKEND_INTERNAL_URL/NEXT_PUBLIC_BACKEND_URL 未配置', { status: 500 });
  }
  const url = new URL(req.url);
  const { slug } = await context.params;
  const first = slug?.[0];
  // 适配旧接口：analysis-config → 新分析模块配置
  if (first === 'analysis-config') {
    const resp = await fetch(`${BACKEND_BASE}/configs/analysis_modules`, { cache: 'no-store' });
    const text = await resp.text();
    return new Response(text, {
      status: resp.status,
      headers: { 'Content-Type': resp.headers.get('Content-Type') || 'application/json' },
    });
  }
  // 适配旧接口：config → 聚合配置
  if (first === 'config') {
    const resp = await fetch(`${FRONTEND_BASE}/api/config`, { cache: 'no-store' });
    const text = await resp.text();
    return new Response(text, { status: resp.status, headers: { 'Content-Type': 'application/json' } });
  }
  // 其他旧 financials 端点在新架构中未实现：返回空对象以避免前端 JSON 解析错误
  return Response.json({}, { status: 200 });
}

export async function PUT(
  req: NextRequest,
  context: { params: Promise<{ slug: string[] }> }
) {
  if (!BACKEND_BASE) {
    return new Response('BACKEND_INTERNAL_URL/NEXT_PUBLIC_BACKEND_URL 未配置', { status: 500 });
  }
  const { slug } = await context.params;
  const first = slug?.[0];
  if (first === 'analysis-config') {
    const body = await req.text();
    const resp = await fetch(`${BACKEND_BASE}/configs/analysis_modules`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body,
    });
    const text = await resp.text();
    return new Response(text, {
      status: resp.status,
      headers: { 'Content-Type': resp.headers.get('Content-Type') || 'application/json' },
    });
  }
  return new Response('Not Found', { status: 404 });
}
