// 健康检查：Readiness（依赖就绪）
// 依据：project_rules §12 可观测性规范、02-architecture-design.md §7 健康检查
// 路径：GET /api/ready
// 检查 api-gateway 可达性（超时 2s）

import { NextResponse } from "next/server";

export const dynamic = "force-dynamic";
export const maxDuration = 5;

export async function GET(): Promise<NextResponse> {
  const gatewayUrl = process.env.API_GATEWAY_URL || "http://localhost:8080";
  const checks: Record<string, "ok" | "fail"> = {};

  // 检查 api-gateway 可达性（仅生产/预览环境，开发环境 mock 跳过）
  const mockEnabled = process.env.NEXT_PUBLIC_API_MOCKING === "enabled";
  if (mockEnabled) {
    checks["api-gateway"] = "ok"; // mock 模式下视为就绪
  } else {
    try {
      const controller = new AbortController();
      const timeout = setTimeout(() => controller.abort(), 2000);
      const res = await fetch(`${gatewayUrl}/healthz`, {
        signal: controller.signal,
      });
      clearTimeout(timeout);
      checks["api-gateway"] = res.ok ? "ok" : "fail";
    } catch {
      checks["api-gateway"] = "fail";
    }
  }

  const allReady = Object.values(checks).every((v) => v === "ok");
  return NextResponse.json(
    { status: allReady ? "ready" : "not_ready", checks, ts: Date.now() },
    { status: allReady ? 200 : 503 },
  );
}
