import { NextRequest } from 'next/server';

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

export async function POST(req: NextRequest) {
  if (!BACKEND_BASE) {
    return new Response('BACKEND_INTERNAL_URL/NEXT_PUBLIC_BACKEND_URL 未配置', { status: 500 });
  }

  try {
    const body = await req.json();
    const { type, data } = body;

    if (!type || !data) {
      return new Response('请求体必须包含 type 和 data', { status: 400 });
    }

    // 将请求转发到 API Gateway
    const targetUrl = `${BACKEND_BASE.replace(/\/$/, '')}/configs/test`;

    const backendRes = await fetch(targetUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ type, ...data }), // 转发时将 data 字段展开
    });

    const backendResBody = await backendRes.text();

    return new Response(backendResBody, {
      status: backendRes.status,
      headers: {
        'Content-Type': 'application/json',
      },
    });

  } catch (error: any) {
    console.error('配置测试代理失败:', error);
    return new Response(JSON.stringify({ success: false, message: error.message || '代理请求时发生未知错误' }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' },
    });
  }
}
