/**
 * Migration: Add currency fields to payment_orders table
 * Adds amount_peso and amount_rmb columns for dual currency support
 */

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

async function up() {
  const queryInterface = sequelize.getQueryInterface();
  
  // Check if columns already exist
  const tableInfo = await queryInterface.describeTable('payment_orders');
  
  if (!tableInfo.amount_peso) {
    await queryInterface.addColumn('payment_orders', 'amount_peso', {
      type: 'DECIMAL(10, 2)',
      allowNull: true,
      defaultValue: null,
      comment: '支付金额（比索）'
    });
    console.log('Added amount_peso column');
  }
  
  if (!tableInfo.amount_rmb) {
    await queryInterface.addColumn('payment_orders', 'amount_rmb', {
      type: 'DECIMAL(10, 2)',
      allowNull: true,
      defaultValue: null,
      comment: '支付金额（人民币）'
    });
    console.log('Added amount_rmb column');
  }
  
  // Make original amount column nullable
  if (tableInfo.amount && !tableInfo.amount.allowNull) {
    await sequelize.query('ALTER TABLE `payment_orders` MODIFY COLUMN `amount` DECIMAL(10, 2) NULL');
    console.log('Made amount column nullable');
  }
  
  console.log('Migration completed successfully');
}

async function down() {
  const queryInterface = sequelize.getQueryInterface();
  
  await queryInterface.removeColumn('payment_orders', 'amount_peso');
  await queryInterface.removeColumn('payment_orders', 'amount_rmb');
  
  console.log('Rollback completed');
}

// Run migration
if (require.main === module) {
  up()
    .then(() => process.exit(0))
    .catch(err => {
      console.error('Migration failed:', err);
      process.exit(1);
    });
}

module.exports = { up, down };
