import { Injectable, OnModuleDestroy, OnModuleInit, Logger } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';
import { tenantGuardExtension } from './tenant-guard.extension';

@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy {
  private readonly logger = new Logger(PrismaService.name);

  constructor() {
    super({
      log: [
        { level: 'warn', emit: 'event' },
        { level: 'error', emit: 'event' },
      ],
    });
    // 纵深防御:$extends 返回扩展客户端,从构造器 return 让 DI 拿到的就是它(透明,
    //   services 的 this.prisma.patient 不用改)。扩展按请求级 ALS 上下文自动注入 tenantId。
    //   $extends 不可变,故只能"构造器 return"这一处接入。
    return this.$extends(tenantGuardExtension) as unknown as PrismaService;
  }

  async onModuleInit(): Promise<void> {
    await this.$connect();
    this.logger.log('Prisma connected');
  }

  async onModuleDestroy(): Promise<void> {
    await this.$disconnect();
  }
}
