import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, resolve } from "node:path";
import { makeExecutableSchema } from "@graphql-tools/schema";
import type { IResolvers } from "@graphql-tools/utils";

/**
 * 加载 GraphQL SDL 契约文件（单一源）。
 *
 * 文件位置：packages/shared-ts/contracts/graphql/parent-bff.graphql
 * 该文件是 parent-bff GraphQL 端点的契约唯一源，前后端共享。
 */
const __dirname = dirname(fileURLToPath(import.meta.url));
const SDL_PATH = resolve(
  __dirname,
  "../../../../packages/shared-ts/contracts/graphql/parent-bff.graphql",
);

const typeDefs = readFileSync(SDL_PATH, "utf-8");

/**
 * 构建 GraphQLSchema（typeDefs + resolvers）。
 *
 * P4.5：resolvers 由 buildResolvers(deps) 生成，注入下游客户端 + ChildGuard。
 * 每次 YOGA_INSTANCE factory 调用时构建一次（应用生命周期内复用）。
 */
export function buildSchema(resolvers: IResolvers) {
  return makeExecutableSchema({
    typeDefs,
    resolvers,
  });
}
