/**
 * 就绪检查端点（ai14，P6 硬化）
 *
 * GET /api/ready — readiness 探针
 * 检查 GraphQL endpoint（经 api-gateway 代理到 student-bff）是否可达。
 * - 就绪：200 + { ready: true, checks: { graphql: true }, timestamp }
 * - 未就绪：503 + { ready: false, checks: { graphql: false }, timestamp }
 */

import { NextResponse } from "next/server";

interface ReadinessResult {
  ready: boolean;
  checks: { graphql: boolean };
  timestamp: string;
}

async function checkGraphql(): Promise<boolean> {
  const gateway =
    process.env.NEXT_PUBLIC_API_GATEWAY_URL ?? "http://localhost:8080";
  const endpoint =
    process.env.NEXT_PUBLIC_GRAPHQL_ENDPOINT ?? "/api/v1/student/graphql";
  const url = `${gateway}${endpoint}`;
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), 3000);
  try {
    const res = await fetch(url, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ query: "{ __typename }" }),
      signal: controller.signal,
    });
    return res.ok;
  } catch {
    return false;
  } finally {
    clearTimeout(timer);
  }
}

export async function GET(): Promise<NextResponse> {
  const graphqlOk = await checkGraphql();
  const result: ReadinessResult = {
    ready: graphqlOk,
    checks: { graphql: graphqlOk },
    timestamp: new Date().toISOString(),
  };
  return NextResponse.json(result, { status: graphqlOk ? 200 : 503 });
}
