import { NextResponse } from "next/server";
import { getMnoteRuntimeConfig } from "@/lib/runtime-config";

export const dynamic = "force-dynamic";

export async function GET() {
  // 说明：浏览器端需要走公网（FRP），但 Next 服务端在本机时应优先走内网/本机（HTTP），
  // 否则会遇到 FRP Auto HTTPS 的自签证书导致 Node fetch 失败。
  const cfg = getMnoteRuntimeConfig();
  const backendUrl =
    process.env.BACKEND_INTERNAL_URL || process.env.BACKEND_URL || cfg.backendUrl;
  if (!backendUrl) {
    return NextResponse.json({ status: "disabled" }, { status: 200 });
  }

  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), 2500);
  try {
    const response = await fetch(`${backendUrl}/health`, {
      method: "GET",
      signal: controller.signal,
    });
    return NextResponse.json({ status: response.ok ? "ok" : "error" }, { status: 200 });
  } catch {
    return NextResponse.json({ status: "error" }, { status: 200 });
  } finally {
    clearTimeout(timer);
  }
}
