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

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

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

  async onModuleInit() {
    await this.$connect()
    this.logger.log('Prisma connected to database')
  }

  async onModuleDestroy() {
    await this.$disconnect()
    this.logger.log('Prisma disconnected from database')
  }

  async cleanDatabase() {
    if (process.env.APP_ENV === 'test') {
      const models = Reflect.ownKeys(this).filter((key) => {
        return (
          typeof key === 'string' &&
          !key.startsWith('_') &&
          !key.startsWith('$') &&
          key !== 'onModuleInit' &&
          key !== 'onModuleDestroy' &&
          key !== 'cleanDatabase'
        )
      })

      for (const model of models) {
        try {
          // @ts-ignore
          await this[model]?.deleteMany?.()
        } catch (error) {
          // Ignore errors for models that don't exist
        }
      }
    }
  }
}
