const { PrismaClient } = require('@prisma/client');

/**
 * Database Connection Wrapper
 * Manages Prisma Client lifecycle
 */
class DatabaseConnection {
  constructor() {
    this.prisma = null;
  }

  /**
   * Initialize Prisma Client
   */
  async connect() {
    if (this.prisma) {
      console.log('⚠️  Prisma Client already connected');
      return;
    }

    try {
      this.prisma = new PrismaClient({
        log: process.env.NODE_ENV === 'development' ? ['query', 'error', 'warn'] : ['error'],
      });

      await this.prisma.$connect();
      console.log('✅ Prisma connected to PostgreSQL');
    } catch (error) {
      console.error('❌ Failed to connect to database:', error);
      throw error;
    }
  }

  /**
   * Get Prisma Client instance
   * @returns {PrismaClient}
   */
  getClient() {
    if (!this.prisma) {
      throw new Error('Database not connected. Call connect() first.');
    }
    return this.prisma;
  }

  /**
   * Close database connection
   */
  async disconnect() {
    if (this.prisma) {
      await this.prisma.$disconnect();
      console.log('🛑 Prisma disconnected');
      this.prisma = null;
    }
  }

  /**
   * Health check
   * @returns {Promise<boolean>}
   */
  async healthCheck() {
    try {
      await this.prisma.$queryRaw`SELECT 1`;
      return true;
    } catch (error) {
      console.error('❌ Database health check failed:', error);
      return false;
    }
  }
}

// Singleton instance
const databaseConnection = new DatabaseConnection();

module.exports = databaseConnection;
