import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';

@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy {
  constructor() {
    super({
      // 根据环境配置日志级别
      // 生产/开发环境：只记录警告和错误,避免大量 SQL 查询日志
      // 测试环境：只记录错误
      // 如需调试 SQL,可临时设置环境变量 PRISMA_LOG_LEVEL=debug
      log: process.env.NODE_ENV === 'test' 
        ? ['error'] 
        : process.env.PRISMA_LOG_LEVEL === 'debug'
        ? ['query', 'info', 'warn', 'error']
        : ['warn', 'error'],
    });
  }

  async onModuleInit() {
    await this.$connect();
  }

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

  /**
   * 清理工具方法 (用于测试)
   */
  async cleanDatabase() {
    if (process.env.NODE_ENV !== 'production') {
      const tablenames = await this.$queryRaw<Array<{ tablename: string }>>`
        SELECT tablename FROM pg_tables WHERE schemaname='public'
      `;

      for (const { tablename } of tablenames) {
        if (tablename !== '_prisma_migrations') {
          try {
            await this.$executeRawUnsafe(`TRUNCATE TABLE "public"."${tablename}" CASCADE;`);
          } catch (error) {
            console.error({ error });
          }
        }
      }
    }
  }
}

