const { sequelize } = require('./config/database');

async function createMissingTables() {
  try {
    console.log('开始创建缺失的表...');

    // 创建loan_applications表
    await sequelize.query(`
      CREATE TABLE IF NOT EXISTS loan_applications (
        id INT AUTO_INCREMENT PRIMARY KEY,
        customer_name VARCHAR(100) NOT NULL COMMENT '客户姓名',
        customer_phone VARCHAR(20) NOT NULL COMMENT '客户电话',
        customer_id_card VARCHAR(18) NOT NULL COMMENT '客户身份证号',
        loan_amount DECIMAL(15,2) NOT NULL COMMENT '贷款金额',
        loan_term INT NOT NULL COMMENT '贷款期限（月）',
        interest_rate DECIMAL(5,2) NOT NULL COMMENT '贷款利率（%）',
        application_date DATE NOT NULL COMMENT '申请日期',
        status ENUM('pending', 'approved', 'rejected', 'completed') DEFAULT 'pending' COMMENT '申请状态',
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
      )
    `, { type: sequelize.QueryTypes.RAW });
    console.log('✅ 创建loan_applications表成功');

    // 创建loan_contracts表
    await sequelize.query(`
      CREATE TABLE IF NOT EXISTS loan_contracts (
        id INT AUTO_INCREMENT PRIMARY KEY,
        contract_number VARCHAR(50) NOT NULL UNIQUE COMMENT '合同编号',
        customer_name VARCHAR(100) NOT NULL COMMENT '客户姓名',
        customer_phone VARCHAR(20) NOT NULL COMMENT '客户电话',
        customer_id_card VARCHAR(18) NOT NULL COMMENT '客户身份证号',
        loan_amount DECIMAL(15,2) NOT NULL COMMENT '贷款金额',
        loan_term INT NOT NULL COMMENT '贷款期限（月）',
        interest_rate DECIMAL(5,2) NOT NULL COMMENT '贷款利率（%）',
        contract_date DATE NOT NULL COMMENT '合同签订日期',
        status ENUM('active', 'completed', 'defaulted', 'cancelled') DEFAULT 'active' COMMENT '合同状态',
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
      )
    `, { type: sequelize.QueryTypes.RAW });
    console.log('✅ 创建loan_contracts表成功');

    // 标记迁移为已完成
    await sequelize.query(`
      INSERT IGNORE INTO SequelizeMeta (name) VALUES 
      ('20241220000006-create-loan-products.js'),
      ('20241220000007-create-loan-applications.js'),
      ('20241220000008-create-audit-records.js'),
      ('20241220000009-create-loan-contracts.js'),
      ('20241220000010-create-employees.js')
    `, { type: sequelize.QueryTypes.RAW });
    console.log('✅ 标记迁移为已完成');

    // 显示所有表
    const tables = await sequelize.query('SHOW TABLES', { type: sequelize.QueryTypes.SELECT });
    console.log('\n当前数据库表:');
    tables.forEach(table => console.log('-', Object.values(table)[0]));

    console.log('\n✅ 所有表创建完成！');
  } catch (error) {
    console.error('❌ 创建表失败:', error.message);
  } finally {
    await sequelize.close();
  }
}

createMissingTables();
