import { PrismaClient } from '@prisma/client';
import { getLogger } from '@stock-bot/logger';

const logger = getLogger('prisma');

// Create a singleton instance of PrismaClient
export const prisma = new PrismaClient({
  log: [
    {
      emit: 'event',
      level: 'query',
    },
    {
      emit: 'event',
      level: 'error',
    },
    {
      emit: 'event',
      level: 'info',
    },
    {
      emit: 'event',
      level: 'warn',
    },
  ],
});

// Log database events in development
if (process.env.NODE_ENV !== 'production') {
  prisma.$on('query', (e: any) => {
    logger.debug('Query', {
      query: e.query,
      params: e.params,
      duration: e.duration,
    });
  });
}

prisma.$on('error', (e: any) => {
  logger.error('Database error', { error: e });
});

prisma.$on('info', (e: any) => {
  logger.info('Database info', { message: e.message });
});

prisma.$on('warn', (e: any) => {
  logger.warn('Database warning', { message: e.message });
});

// Graceful shutdown
process.on('beforeExit', async () => {
  await prisma.$disconnect();
  logger.info('Prisma disconnected');
});
