import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";

/**
 * 仅 `next dev` 生效：把 FastAPI 同名路由代理到本机 uvicorn。
 * 生产环境由 FastAPI 托管 web-console/out，浏览器与 API 同域，不需要本中间件。
 */
const TARGET = process.env.API_PROXY_TARGET || "http://127.0.0.1:8001";

const API_ROOTS = new Set([
  "process_monitor",
  "server_info",
  "health",
  "status",
  "start",
  "stop",
  "restart",
  "get_config",
  "save_config",
  "get_url_config",
  "save_url_config",
]);

export function middleware(request: NextRequest) {
  if (process.env.NODE_ENV !== "development") {
    return NextResponse.next();
  }
  const path = request.nextUrl.pathname;
  const root = path.split("/").filter(Boolean)[0] ?? "";
  if (!API_ROOTS.has(root)) {
    return NextResponse.next();
  }
  const dest = new URL(path + request.nextUrl.search, TARGET);
  return NextResponse.rewrite(dest);
}

export const config = {
  matcher: [
    "/process_monitor",
    "/server_info",
    "/health",
    "/status",
    "/start",
    "/stop",
    "/restart",
    "/get_config",
    "/save_config",
    "/get_url_config",
    "/save_url_config",
  ],
};
