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

async function migrateCommissionField() {
  try {
    console.log('Starting migration: foreman_commission_percentage -> foreman_commission_amount');
    
    // Check if the old column exists
    const [results] = await sequelize.query(`
      SELECT column_name 
      FROM information_schema.columns 
      WHERE table_name = 'chit_groups' 
      AND column_name = 'foreman_commission_percentage'
    `);
    
    if (results.length > 0) {
      console.log('Old column found. Starting migration...');
      
      // Add new column
      await sequelize.query(`
        ALTER TABLE chit_groups 
        ADD COLUMN foreman_commission_amount DECIMAL(10,2)
      `);
      
      // Convert percentage to fixed amount (assuming 5% default for existing records)
      await sequelize.query(`
        UPDATE chit_groups 
        SET foreman_commission_amount = (total_value * foreman_commission_percentage / 100)
        WHERE foreman_commission_percentage IS NOT NULL
      `);
      
      // Set default value for any NULL records
      await sequelize.query(`
        UPDATE chit_groups 
        SET foreman_commission_amount = 250 
        WHERE foreman_commission_amount IS NULL
      `);
      
      // Make new column NOT NULL
      await sequelize.query(`
        ALTER TABLE chit_groups 
        ALTER COLUMN foreman_commission_amount SET NOT NULL
      `);
      
      // Drop old column
      await sequelize.query(`
        ALTER TABLE chit_groups 
        DROP COLUMN foreman_commission_percentage
      `);
      
      console.log('Migration completed successfully!');
    } else {
      console.log('Old column not found. Checking if new column exists...');
      
      const [newResults] = await sequelize.query(`
        SELECT column_name 
        FROM information_schema.columns 
        WHERE table_name = 'chit_groups' 
        AND column_name = 'foreman_commission_amount'
      `);
      
      if (newResults.length > 0) {
        console.log('New column already exists. Migration not needed.');
      } else {
        console.log('Neither column exists. Creating new column...');
        
        await sequelize.query(`
          ALTER TABLE chit_groups 
          ADD COLUMN foreman_commission_amount DECIMAL(10,2) NOT NULL DEFAULT 250
        `);
        
        console.log('New column created successfully!');
      }
    }
    
  } catch (error) {
    console.error('Migration failed:', error);
  } finally {
    await sequelize.close();
  }
}

migrateCommissionField();
