import { Injectable, Logger, OnModuleDestroy, type OnModuleInit } 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: [{ emit: 'event', level: 'warn' }, { emit: 'event', level: 'error' }] });
  }

  // `emit: 'event'` above routes Prisma's own warnings and errors to listeners
  // instead of stdout. Without these two there are no listeners, so they went
  // nowhere at all — the quietest possible way to lose a connection-pool
  // exhaustion or a failing query.
  onModuleInit(): void {
    this.$on('warn' as never, (e: { message: string }) => this.logger.warn(e.message));
    this.$on('error' as never, (e: { message: string }) => this.logger.error(e.message));
  }

  // Intentionally NOT connecting in onModuleInit: Prisma connects lazily on the
  // first query, so the API can boot even when the database is unreachable.
  // Liveness and readiness are reported separately by the health endpoint.

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

  async isHealthy(): Promise<boolean> {
    try {
      await this.$queryRaw`SELECT 1`;
      return true;
    } catch (err) {
      this.logger.warn(`Database not reachable: ${(err as Error).message}`);
      return false;
    }
  }
}
