/**
 * StudentModule - 装配 GraphQL Yoga + Resolver.
 *
 * 仲裁依据:
 *   - coord-final-decisions §2 B1 (P2 起直接 GraphQL Yoga + DataLoader)
 *   - coord-final-decisions §2 B8 (复用 shared-ts DownstreamClient)
 *
 * 职责:
 *   1. 启动时创建 GraphQL Yoga 实例 (加载 schema + 装配 resolver)
 *   2. 提供 Yoga Express middleware 挂载钩子 (由 main.ts 调用)
 *   3. 不直接持有 resolver 实例 (resolver 是纯函数, 通过 context 注入依赖)
 */
import { Module, OnModuleInit } from "@nestjs/common";
import { Inject } from "@nestjs/common";
import { DownstreamClient } from "@edu/shared-ts/bff";
import { REDIS_CLIENT, CacheService } from "../shared/cache/cache.module.js";
import type { Redis } from "ioredis";
import {
  createStudentBffYoga,
  type StudentBffContext,
} from "../shared/graphql/yoga.js";
import { studentBffResolvers } from "./resolvers/index.js";
import { logger } from "../shared/observability/logger.js";
import type { YogaServerInstance } from "graphql-yoga";
import type { Request, Response } from "express";

export const GRAPHQL_YOGA = Symbol("GRAPHQL_YOGA");

@Module({
  providers: [
    {
      provide: GRAPHQL_YOGA,
      useFactory: async (
        downstream: DownstreamClient,
        redis: Redis,
      ): Promise<
        YogaServerInstance<{ req: Request; res: Response }, StudentBffContext>
      > => {
        const cache = new CacheService(redis);
        return createStudentBffYoga(
          studentBffResolvers,
          downstream,
          redis,
          cache,
        );
      },
      inject: [DownstreamClient, REDIS_CLIENT],
    },
  ],
  exports: [GRAPHQL_YOGA],
})
export class StudentModule implements OnModuleInit {
  constructor(@Inject(GRAPHQL_YOGA) private readonly yoga: Promise<unknown>) {}

  async onModuleInit(): Promise<void> {
    // 确保 Yoga 实例初始化完成
    await this.yoga;
    logger.info("StudentModule initialized, GraphQL Yoga ready");
  }
}
