/**
 * Prisma 客户端单例
 * 避免多个实例导致数据库连接泄漏
 */

import pkg from '@prisma/client';
const { PrismaClient } = pkg;

let prismaInstance = null;

/**
 * 获取 PrismaClient 单例
 * @returns {PrismaClient} PrismaClient 实例
 */
export function getPrisma() {
  if (!prismaInstance) {
    prismaInstance = new PrismaClient({
      log: process.env.NODE_ENV === 'development'
        ? ['query', 'error', 'warn']
        : ['error'],
    });

    // 优雅关闭处理
    process.on('beforeExit', async () => {
      await prismaInstance.$disconnect();
    });
  }

  return prismaInstance;
}

// 导出单例实例
export const prisma = getPrisma();

/**
 * 初始化数据库连接
 * @returns {Promise<boolean>} 是否成功连接
 */
export async function initDatabase() {
  try {
    await prisma.$connect();
    console.log('[Prisma] Database connected');
    return true;
  } catch (error) {
    console.error('[Prisma] Database connection failed:', error.message);
    return false;
  }
}

export default prisma;