/**
 * Prisma client singleton
 * Prevents multiple instances of PrismaClient in development
 */

import { isMemoryMode } from '../config/persistence.js';

// Use any type to avoid build-time errors when Prisma client isn't generated yet
// The actual PrismaClient type will be available at runtime
let prismaClient: any = null;

/**
 * Get or create Prisma client singleton
 * Throws an error if called in memory mode
 */
export async function getPrismaClient(): Promise<any> {
  if (isMemoryMode()) {
    throw new Error(
      'Cannot initialize Prisma client in memory mode. ' +
      'Set GATEWAY_PERSISTENCE=postgres to use PostgreSQL.'
    );
  }
  
  if (!prismaClient) {
    // Dynamic import to get PrismaClient at runtime (ES module compatible)
    // This avoids build-time errors when Prisma client isn't generated yet
    const prismaModule = await import('@prisma/client') as any;
    const PrismaClientConstructor = prismaModule.PrismaClient || (prismaModule as any).default?.PrismaClient;
    if (!PrismaClientConstructor) {
      throw new Error('PrismaClient not found in @prisma/client. Make sure Prisma client is generated: pnpm db:generate');
    }
    prismaClient = new PrismaClientConstructor({
      log: process.env['NODE_ENV'] === 'development' 
        ? ['query', 'error', 'warn'] 
        : ['error'],
    });
  }
  
  return prismaClient;
}

/**
 * Disconnect Prisma client (for cleanup on shutdown)
 */
export async function disconnectPrisma(): Promise<void> {
  if (prismaClient) {
    await prismaClient.$disconnect();
    prismaClient = null;
  }
}

/**
 * Check if Prisma client is initialized
 */
export function isPrismaInitialized(): boolean {
  return prismaClient !== null;
}

