const { Sequelize } = require('sequelize');

// 从环境变量获取数据库配置
const dialect = process.env.DB_DIALECT || 'mysql';
const config = {
  logging: console.log, // 启用SQL日志
  define: {
    timestamps: true,
    underscored: false,
    freezeTableName: true
  }
};

// 根据数据库类型配置不同的选项
if (dialect === 'sqlite') {
  config.storage = process.env.DB_STORAGE || './bank_database.sqlite';
  config.dialect = 'sqlite';
} else {
  config.host = process.env.DB_HOST || '129.211.213.226';
  config.port = process.env.DB_PORT || 9527;
  config.dialect = 'mysql';
  config.timezone = '+08:00';
  config.define.charset = 'utf8mb4';
  config.define.collate = 'utf8mb4_unicode_ci';
  config.pool = {
    max: 10,
    min: 0,
    acquire: 30000,
    idle: 10000
  };
}

let sequelize;
if (dialect === 'sqlite') {
  sequelize = new Sequelize(config);
} else {
  sequelize = new Sequelize(
    process.env.DB_NAME || 'ningxia_bank',
    process.env.DB_USER || 'root',
    process.env.DB_PASSWORD || 'aiotAiot123!',
    config
  );
}

// 测试数据库连接（最多重试3次）
const MAX_RETRIES = 3;
let retryCount = 0;

const testConnection = async () => {
  try {
    await sequelize.authenticate();
    console.log('✅ 银行系统数据库连接成功');
  } catch (err) {
    console.error('❌ 银行系统数据库连接失败:', err.message);
    if (retryCount < MAX_RETRIES) {
      retryCount++;
      console.log(`🔄 正在重试连接 (${retryCount}/${MAX_RETRIES})...`);
      setTimeout(testConnection, 5000); // 5秒后重试
    } else {
      console.error('❌ 数据库连接失败，应用将使用模拟数据运行');
    }
  }
};

// 异步测试连接，不阻塞应用启动
testConnection().catch(() => {
  console.log('📊 数据库连接测试完成，应用继续启动');
});

// 兼容导出：同时支持 require('.../database') 和 const { sequelize } = require('.../database')
module.exports = sequelize;
module.exports.sequelize = sequelize;