/**
 * 就绪检查 - Readiness
 *
 * GET /api/ready
 * 检查依赖服务可达性（开发期直接返回 200）
 */
import { NextResponse } from "next/server";

export const dynamic = "force-dynamic";

export async function GET(): Promise<NextResponse> {
  // 开发期：MSW 启用时直接就绪
  if (process.env.NEXT_PUBLIC_API_MOCKING === "enabled") {
    return NextResponse.json({
      status: "ready",
      service: "admin-portal",
      dependencies: { gateway: "mocked" },
      timestamp: Date.now(),
    });
  }

  // 生产：检查 api-gateway 可达性
  const gatewayUrl = process.env.API_GATEWAY_URL ?? "http://localhost:8080";
  try {
    const res = await fetch(`${gatewayUrl}/healthz`, {
      signal: AbortSignal.timeout(2000),
    });
    if (!res.ok) throw new Error(`gateway status ${res.status}`);
    return NextResponse.json({
      status: "ready",
      service: "admin-portal",
      dependencies: { gateway: "ok" },
      timestamp: Date.now(),
    });
  } catch (err) {
    return NextResponse.json(
      {
        status: "not_ready",
        service: "admin-portal",
        dependencies: { gateway: "unreachable" },
        error: err instanceof Error ? err.message : String(err),
        timestamp: Date.now(),
      },
      { status: 503 },
    );
  }
}
