/**
 * 数据库初始化脚本
 */

import { prisma } from './client.js';

/**
 * 测试数据库连接
 * @returns {Promise<boolean>} 连接是否成功
 */
export async function testConnection() {
  try {
    await prisma.$queryRaw`SELECT 1`;
    console.log('[DB] Database connection successful');
    return true;
  } catch (error) {
    console.error('[DB] Database connection failed:', error.message);
    return false;
  }
}

/**
 * 初始化数据库
 * - 测试连接
 * - 可选：创建默认数据
 */
export async function initDatabase() {
  console.log('[DB] Initializing database...');

  const connected = await testConnection();
  if (!connected) {
    throw new Error('Failed to connect to database');
  }

  console.log('[DB] Database initialized successfully');
  return true;
}

/**
 * 优雅关闭数据库连接
 */
export async function closeDatabase() {
  try {
    await prisma.$disconnect();
    console.log('[DB] Database connection closed');
  } catch (error) {
    console.error('[DB] Error closing database connection:', error.message);
  }
}

export default { initDatabase, testConnection, closeDatabase };