import db from "../models/index.js";

/**
 * Robust fee calculator that checks merchant-specific overrides, 
 * then global DB settings, then system fallbacks.
 */
export const calculateSaaSFee = async (type, amount, merchantId = null) => {
    try {
        const { Merchant, Setting } = db;
        let feeRate = null;
        let feeCap = null;
        let flatFee = null;

        // 1. Check for Merchant-specific overrides
        if (merchantId) {
            const merchant = await Merchant.findByPk(merchantId);
            if (merchant) {
                if (type === "deposit" && merchant.customDepositFeePercent !== null) {
                    feeRate = parseFloat(merchant.customDepositFeePercent);
                    feeCap = merchant.customDepositFeeCap !== null ? parseFloat(merchant.customDepositFeeCap) : null;
                } else if (type === "payout" && merchant.customPayoutFeeFlat !== null) {
                    flatFee = parseFloat(merchant.customPayoutFeeFlat);
                }
            }
        }

        // 2. Fetch from global Settings if not overridden
        if (type === "deposit" && feeRate === null) {
            const percentSetting = await Setting.findOne({ where: { key: "deposit_fee_percent" } });
            const capSetting = await Setting.findOne({ where: { key: "deposit_fee_cap" } });
            
            feeRate = percentSetting ? parseFloat(percentSetting.value) : 0.5; // fallback to 0.5%
            feeCap = capSetting ? parseFloat(capSetting.value) : 100; // fallback to 100
        } else if (type === "payout" && flatFee === null) {
            const flatSetting = await Setting.findOne({ where: { key: "payout_fee_flat" } });
            flatFee = flatSetting ? parseFloat(flatSetting.value) : 20; // fallback to 20
        }

        // 3. Final Calculation
        let stampDuty = 0;
        if (type === "payout" && parseFloat(amount) >= 10000) {
            stampDuty = 50;
        }

        if (type === "deposit") {
            let calculatedFee = (parseFloat(amount) * feeRate) / 100;
            if (feeCap !== null && calculatedFee > feeCap) {
                calculatedFee = feeCap;
            }
            return { fee: calculatedFee, stampDuty: 0 };
        }

        if (type === "payout") {
            return { fee: flatFee, stampDuty };
        }

        if (type === "merchant_debit") {
            return { fee: 0, stampDuty: 0 };
        }

        return { fee: 0, stampDuty: 0 };
    } catch (error) {
        console.error("❌ Fee calculation error, using fallbacks:", error.message);
        // Direct hardcoded fallbacks in case of DB failure
        if (type === "deposit") {
            let fee = (parseFloat(amount) * 0.5) / 100;
            fee = fee > 100 ? 100 : fee;
            return { fee, stampDuty: 0 };
        }
        
        const stampDuty = (type === "payout" && parseFloat(amount) >= 10000) ? 50 : 0;
        return { fee: 20, stampDuty };
    }
};
