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

/**
 * Adjusts a merchant's balance for a specific non-NGN currency wallet.
 * Automatically creates the wallet record if it does not already exist (lazy init).
 * NGN is never handled here — that's Merchant.balance directly.
 *
 * @param {string} merchantId - The merchant UUID
 * @param {string} currency - Currency code, e.g. 'USD'
 * @param {number} delta - Positive to credit, negative to debit
 * @param {object} [transaction] - Optional Sequelize transaction object for atomicity
 * @returns {Promise<object>} The updated MerchantWalletBalance record
 */
export async function adjustMerchantWalletBalance(merchantId, currency, delta, transaction = null) {
  const [walletRecord] = await db.MerchantWalletBalance.findOrCreate({
    where: { merchantId, currency },
    defaults: { balance: 0.00, prev_balance: 0.00, status: "active" },
    ...(transaction && { transaction }),
  });

  const newBalance = parseFloat(walletRecord.balance) + parseFloat(delta);

  if (newBalance < 0) {
    throw new Error(`Insufficient ${currency} wallet balance. Available: ${walletRecord.balance}`);
  }

  await walletRecord.update(
    { prev_balance: walletRecord.balance, balance: newBalance },
    transaction ? { transaction } : {},
  );

  return walletRecord;
}

/**
 * Fetch a merchant's current balance for a specific non-NGN currency wallet.
 * Returns { balance: 0, prev_balance: 0 } if no record yet.
 *
 * @param {string} merchantId
 * @param {string} currency
 * @returns {Promise<{ balance: number, prev_balance: number }>}
 */
export async function getMerchantWalletBalance(merchantId, currency) {
  const record = await db.MerchantWalletBalance.findOne({
    where: { merchantId, currency },
  });

  return {
    balance: record ? parseFloat(record.balance) : 0.00,
    prev_balance: record ? parseFloat(record.prev_balance) : 0.00,
  };
}
