import { Injectable, Logger, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';
import { resolvePrismaSlowQueryThreshold, shouldLogPrismaQuery } from './prisma-monitoring';

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

  constructor() {
    super({
      log: [{ emit: 'event', level: 'query' }],
    });

    (this as any).$on('query', (event: { duration: number; query: string }) => {
      if (!shouldLogPrismaQuery(event.duration, this.slowQueryThresholdMs)) return;
      this.logger.warn(`Slow Prisma query: ${event.duration}ms ${event.query}`);
    });
  }

  async onModuleInit() {
    try {
      await this.$connect();
      this.connected = true;
      this.logger.log('Prisma connected');
    } catch (e: any) {
      this.logger.warn(
        `数据库连接失败 (${e?.errorCode || e?.message || e}) — 跳过，需要 DB 的接口将不可用，但不影响 AI 配置 / 拆解模块`,
      );
    }
  }

  async onModuleDestroy() {
    if (this.connected) {
      await this.$disconnect();
    }
  }
}
