// 健康检查模块（G3 + president §2.4）
// P2 注册 2 项探针：Redis + iam gRPC
// P3+ 扩展：core-edu / content / data-ana / ai / msg（按阶段新增）
import { Module, OnModuleInit, OnModuleDestroy } from "@nestjs/common";
import { Redis } from "ioredis";
import { env } from "../../config/env.js";
import { logger } from "../observability/logger.js";
import { HealthController } from "./health.controller.js";
import { healthRegistry } from "./readiness.probe.js";
import { RedisHealthProbe } from "./redis.probe.js";
import { IamGrpcHealthProbe } from "./iam-grpc.probe.js";
import { ClientsModule } from "../../clients/clients.module.js";

@Module({
  imports: [ClientsModule],
  controllers: [HealthController],
  providers: [IamGrpcHealthProbe],
})
export class HealthModule implements OnModuleInit, OnModuleDestroy {
  private redis: Redis | null = null;

  constructor(private readonly iamProbe: IamGrpcHealthProbe) {}

  async onModuleInit(): Promise<void> {
    // 注册 Redis 探针（必需依赖）
    this.redis = new Redis(env.REDIS_URL, {
      maxRetriesPerRequest: 3,
      lazyConnect: false,
      connectTimeout: 5000,
    });
    const redisProbe = new RedisHealthProbe(this.redis);
    healthRegistry.register(redisProbe);
    logger.info({ probe: "redis", required: true }, "Health probe registered");

    // 注册 iam gRPC 探针（必需依赖）
    healthRegistry.register(this.iamProbe);
    logger.info(
      { probe: "iam-grpc", required: true, target: env.IAM_GRPC_TARGET },
      "Health probe registered",
    );
  }

  async onModuleDestroy(): Promise<void> {
    if (this.redis) {
      await this.redis.quit();
      logger.info("Redis connection closed");
    }
  }
}
