using Unity.Collections;
using Unity.Entities;
namespace ProjectM.Simulation
{
///
/// Shared harvest-yield deposit routing used by BOTH the projectile-sweep harvest (ResourceHarvestSystem) and
/// the melee-cone harvest (MeleeComboSystem), so the two can't drift. (They previously did: the melee path
/// hard-coded and silently ignored per-item stack caps.) Base-region yield
/// credits the shared ledger DIRECTLY (the build-currency pool); expedition / un-tagged yield routes to the
/// harvesting player's PERSONAL inventory — per-item StackMax from the item catalog, fallback DefaultStackMax —
/// and spills any overflow to the ledger (the no-loss valve). Pure + Burst-friendly.
///
public static class HarvestMath
{
///
/// Routes one harvested yield to its sink. Returns true if the yield landed somewhere (inventory or ledger);
/// callers use this to avoid consuming a target for zero credit (e.g. no ledger singleton present).
/// may be (unresolvable owner) — the yield then falls
/// through to the ledger. is only touched when is true.
///
public static bool DepositYield(
byte yieldId, int amount, bool toLedger, Entity player,
BufferLookup invLookup,
DynamicBuffer ledger, bool haveLedger,
bool haveDb, in ItemDatabase itemDb)
{
int remainder = amount;
bool deposited = false;
if (!toLedger && player != Entity.Null && invLookup.HasBuffer(player))
{
int stackMax = Tuning.DefaultStackMax;
if (haveDb && itemDb.Value.IsCreated)
{
ref var blob = ref itemDb.Value.Value;
if (blob.TryGetItem(yieldId, out var def) && def.StackMax > 0)
stackMax = def.StackMax;
}
var inv = invLookup[player];
remainder = InventoryMath.Deposit(inv, yieldId, amount, stackMax, Tuning.InventoryMaxSlots);
deposited = true;
}
if (remainder > 0 && haveLedger)
{
StorageMath.Deposit(ledger, yieldId, remainder);
deposited = true;
}
return deposited;
}
}
}