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

@Injectable()
export class PrismaService extends PrismaClient implements OnModuleDestroy {
  constructor(private readonly config: ConfigService) {
    const url = config.get<string>('database.url') ?? process.env.DATABASE_URL;

    super({
      ...(url ? { datasources: { db: { url } } } : {}),
      log:
        config.get<'development' | 'test' | 'production'>('app.env') ===
        'development'
          ? ['warn', 'error']
          : ['error'],
    });
  }

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