'use strict';

/**
 * Consumo modular de comida das tropas.
 *
 * Todas as tropas pertencentes ao jogador consomem comida, estejam:
 * - disponíveis no castelo;
 * - em viagem para atacar;
 * - a regressar ao castelo;
 * - numa marcha cancelada de regresso.
 *
 * As tropas em marcha são retiradas temporariamente de profile.troops, por isso
 * são contabilizadas através de profile.missions sem duplicar unidades.
 */
(() => {
  const VERSION = 2;
  const FOOD_PER_UNIT_PER_HOUR = 2;

  function safeCount(value) {
    return Math.max(0, Math.floor(Number(value) || 0));
  }

  function troopCollectionTotal(troops) {
    return Object.values(troops || {}).reduce((sum, value) => sum + safeCount(value), 0);
  }

  function castleUnits(profile) {
    return troopCollectionTotal(profile?.troops);
  }

  function isActiveMission(mission) {
    if (!mission || typeof mission !== 'object') return false;
    return mission.state !== 'done';
  }

  function marchingUnits(profile) {
    return (Array.isArray(profile?.missions) ? profile.missions : [])
      .filter(isActiveMission)
      .reduce((sum, mission) => sum + troopCollectionTotal(mission.troops), 0);
  }

  function totalUnits(profile) {
    return castleUnits(profile) + marchingUnits(profile);
  }

  function hourlyConsumption(profile) {
    return totalUnits(profile) * FOOD_PER_UNIT_PER_HOUR;
  }

  function consumptionForUnits(units) {
    return safeCount(units) * FOOD_PER_UNIT_PER_HOUR;
  }

  function applyToRates(rates, profile) {
    if (!rates || typeof rates !== 'object') return rates;
    rates.food = (Number(rates.food) || 0) - hourlyConsumption(profile);
    return rates;
  }

  function formatSignedRate(value, format = value => String(Math.floor(value))) {
    const numeric = Number(value) || 0;
    const sign = numeric > 0 ? '+' : numeric < 0 ? '−' : '';
    return `${sign}${format(Math.abs(numeric))}/h`;
  }

  globalThis.ReinosTroopUpkeep = Object.freeze({
    VERSION,
    FOOD_PER_UNIT_PER_HOUR,
    castleUnits,
    marchingUnits,
    totalUnits,
    hourlyConsumption,
    consumptionForUnits,
    applyToRates,
    formatSignedRate
  });
})();
