const { Sequelize } = require('sequelize');
const config = require('./index.js');

const sequelize = new Sequelize(
  config.DB_CONFIG.database,
  config.DB_CONFIG.user,
  config.DB_CONFIG.password,
  {
    host: config.DB_CONFIG.host,
    port: config.DB_CONFIG.port,
    dialect: config.DB_CONFIG.dialect,
    logging: process.env.NODE_ENV === 'development' ? console.log : false,
    pool: {
      max: 5,
      min: 0,
      acquire: 30000,
      idle: 10000
    },
    define: {
      timestamps: true,
      paranoid: true,
      underscored: true,
      freezeTableName: true
    },
    timezone: '+08:00' // 设置为中国时区
  }
);

// 测试数据库连接
async function testConnection() {
  try {
    await sequelize.authenticate();
    console.log('数据库连接成功');
    return true;
  } catch (error) {
    console.error('数据库连接失败:', error);
    return false;
  }
}

// 先导出sequelize实例
const db = sequelize;

// 再添加测试连接方法
db.testConnection = testConnection;

module.exports = db;