/**
 * Auto-sell inventory items below the user's configured threshold.
 * Returns sold items and total credits added (caller updates balance).
 * Prestige gain bonus multiplies credited amount (not the sell threshold check).
 */
import { applyGainMultiplier } from './prestige.js';
import { toCentsBigInt, centsJson } from './cents.js';

export function shouldAutoSell(user, valueCents) {
  if (!user?.autoSellEnabled) return false;
  const threshold = toCentsBigInt(user.autoSellThresholdCents ?? 0);
  return toCentsBigInt(valueCents) < threshold;
}

/** Compute auto-sell payout without mutating inventory (for deferred claims). */
export function computeAutoSell(user, inventoryItems) {
  if (!user?.autoSellEnabled) {
    return { sold: [], balanceDelta: 0n };
  }

  const threshold = toCentsBigInt(user.autoSellThresholdCents ?? 0);
  const gainBonus = user.prestigeGainBonus ?? 0;
  const sold = [];
  let balanceDelta = 0n;

  for (const inv of inventoryItems) {
    if (!inv || inv.locked || inv.staked || inv.favorite) continue;
    const value = toCentsBigInt(inv.valueCents);
    if (value >= threshold) continue;
    sold.push(inv);
    balanceDelta += applyGainMultiplier(value, gainBonus);
  }

  return { sold, balanceDelta };
}

export async function applyAutoSell(tx, user, inventoryItems) {
  const { sold, balanceDelta } = computeAutoSell(user, inventoryItems);
  const gainBonus = user.prestigeGainBonus ?? 0;

  if (!sold.length) {
    return { sold: [], balanceDelta: 0n };
  }

  const soldIds = sold.map((inv) => inv.id);
  await tx.inventoryItem.deleteMany({
    where: { id: { in: soldIds }, userId: user.id },
  });
  await tx.transaction.create({
    data: {
      userId: user.id,
      type: 'sell_item',
      amount: centsJson(balanceDelta),
      meta: JSON.stringify({
        count: sold.length,
        inventoryItemIds: soldIds,
        autoSell: true,
        prestigeGainBonus: gainBonus,
        payout: centsJson(balanceDelta),
      }),
    },
  });

  return { sold, balanceDelta };
}
