const { Sequelize } = require('sequelize');
require('dotenv').config();

// 创建Sequelize实例
const sequelize = new Sequelize({
  dialect: process.env.DB_DIALECT || 'mysql',
  host: process.env.DB_HOST || '129.211.213.226',
  port: process.env.DB_PORT || 9527,
  database: process.env.DB_DATABASE || 'insurance_data',
  username: process.env.DB_USER || 'root',
  password: process.env.DB_PASSWORD || 'aiotAiot123!',
  logging: process.env.NODE_ENV === 'development' ? console.log : false,
  pool: {
    max: 10,
    min: 0,
    acquire: 30000,
    idle: 10000
  },
  define: {
    timestamps: true,
    underscored: true,
    charset: 'utf8mb4',
    collate: 'utf8mb4_unicode_ci'
  },
  dialectOptions: {
    // 解决MySQL严格模式问题
    dateStrings: true,
    typeCast: true,
    // 允许0000-00-00日期值
    connectAttributes: {
      sql_mode: 'TRADITIONAL'
    }
  },
  timezone: '+08:00' // 设置时区为东八区
});

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

module.exports = { sequelize, testConnection };