/**
 * Script to fix dual-currency commissions for existing payment orders
 * 
 * This script finds payment orders that have both amountRmb and amountPeso,
 * but only have one commission record, and creates the missing commission.
 * 
 * Usage: node src/scripts/fixDualCurrencyCommissions.js [--dry-run]
 */

const { sequelize } = require('../config/database');
const PaymentOrder = require('../models/PaymentOrder');
const Commission = require('../models/Commission');
const User = require('../models/User');
const commissionConfigService = require('../services/commissionConfigService');

const isDryRun = process.argv.includes('--dry-run');

async function fixDualCurrencyCommissions() {
  console.log('=== Fix Dual Currency Commissions ===');
  console.log(`Mode: ${isDryRun ? 'DRY RUN (no changes will be made)' : 'LIVE'}`);
  console.log('');

  try {
    // Find all active payment orders with both currencies
    const orders = await PaymentOrder.findAll({
      where: {
        status: 'active',
      },
      include: [
        {
          model: User,
          as: 'user',
          attributes: ['id', 'invitedBy'],
        },
      ],
    });

    console.log(`Found ${orders.length} active payment orders`);

    let fixedCount = 0;
    let skippedCount = 0;

    for (const order of orders) {
      const amountRmb = parseFloat(order.amountRmb || 0);
      const amountPeso = parseFloat(order.amountPeso || 0);
      const legacyAmount = parseFloat(order.amount || 0);

      // Check if order has both currencies
      const hasRmb = amountRmb > 0 || legacyAmount > 0;
      const hasPeso = amountPeso > 0;

      if (!hasRmb && !hasPeso) {
        continue; // No amounts, skip
      }

      // Check if user was invited
      if (!order.user || !order.user.invitedBy) {
        continue; // No inviter, skip
      }

      // Get existing commissions for this order
      const existingCommissions = await Commission.findAll({
        where: { paymentOrderId: order.id },
      });

      const existingCurrencies = existingCommissions.map(c => c.currency || 'RMB');
      const hasRmbCommission = existingCurrencies.includes('RMB');
      const hasPhpCommission = existingCurrencies.includes('PHP');

      // Check if we need to create missing commissions
      const needsRmbCommission = hasRmb && !hasRmbCommission;
      const needsPhpCommission = hasPeso && !hasPhpCommission;

      if (!needsRmbCommission && !needsPhpCommission) {
        continue; // All commissions exist, skip
      }

      console.log(`\nOrder ${order.orderNo}:`);
      console.log(`  - amountRmb: ${amountRmb}, amountPeso: ${amountPeso}, amount: ${legacyAmount}`);
      console.log(`  - Existing commissions: ${existingCurrencies.join(', ') || 'none'}`);
      console.log(`  - Needs RMB commission: ${needsRmbCommission}`);
      console.log(`  - Needs PHP commission: ${needsPhpCommission}`);

      if (isDryRun) {
        console.log(`  - [DRY RUN] Would create missing commissions`);
        fixedCount++;
        continue;
      }

      // Get commission rate (use existing rate if available, otherwise get current rate)
      let commissionRate;
      if (existingCommissions.length > 0) {
        commissionRate = parseFloat(existingCommissions[0].commissionRate);
      } else {
        commissionRate = await commissionConfigService.getCommissionRate();
      }

      const transaction = await sequelize.transaction();

      try {
        const inviter = await User.findByPk(order.user.invitedBy, { transaction });

        if (needsRmbCommission) {
          const rmbPaymentAmount = amountRmb > 0 ? amountRmb : legacyAmount;
          const rmbCommissionAmount = rmbPaymentAmount * commissionRate;

          await Commission.create({
            inviterId: order.user.invitedBy,
            inviteeId: order.user.id,
            paymentOrderId: order.id,
            paymentAmount: rmbPaymentAmount,
            commissionRate: commissionRate,
            commissionAmount: rmbCommissionAmount,
            currency: 'RMB',
            status: 'credited',
          }, { transaction });

          if (inviter) {
            inviter.balance = parseFloat(inviter.balance || 0) + rmbCommissionAmount;
          }

          console.log(`  - Created RMB commission: ¥${rmbCommissionAmount.toFixed(2)}`);
        }

        if (needsPhpCommission) {
          const phpCommissionAmount = amountPeso * commissionRate;

          await Commission.create({
            inviterId: order.user.invitedBy,
            inviteeId: order.user.id,
            paymentOrderId: order.id,
            paymentAmount: amountPeso,
            commissionRate: commissionRate,
            commissionAmount: phpCommissionAmount,
            currency: 'PHP',
            status: 'credited',
          }, { transaction });

          if (inviter) {
            inviter.balancePeso = parseFloat(inviter.balancePeso || 0) + phpCommissionAmount;
          }

          console.log(`  - Created PHP commission: ₱${phpCommissionAmount.toFixed(2)}`);
        }

        if (inviter) {
          await inviter.save({ transaction });
        }

        await transaction.commit();
        fixedCount++;
        console.log(`  - ✓ Fixed successfully`);
      } catch (error) {
        await transaction.rollback();
        console.error(`  - ✗ Error: ${error.message}`);
        skippedCount++;
      }
    }

    console.log('\n=== Summary ===');
    console.log(`Fixed: ${fixedCount}`);
    console.log(`Skipped/Errors: ${skippedCount}`);

    if (isDryRun) {
      console.log('\nThis was a dry run. Run without --dry-run to apply changes.');
    }

  } catch (error) {
    console.error('Error:', error);
  } finally {
    await sequelize.close();
  }
}

fixDualCurrencyCommissions();
