namespace ReactorMaintenance.Simulation;

internal static class LeakSystem
{
    public static LevelState Inject(LevelState level)
    {
        var surface = level.Surface.ToArray();
        foreach (var leak in level.Leaks.Where(leak => !leak.Repaired))
        {
            var underground = level.GetUnderground(leak.UndergroundPosition, leak.Carrier);
            if (underground.State != EUndergroundState.Leaking)
                continue;

            var accessIndex = level.Index(leak.AccessPosition);
            if (surface[accessIndex].Blocks(leak.Carrier))
                continue;

            var amount = Balancing.Current.LeakBaseAmount + (underground.Amount * Balancing.Current.LeakAmountScale) + (underground.Intensity * Balancing.Current.LeakIntensityScale);
            surface[accessIndex] = SurfaceCarrierMath.AddCarrier(surface[accessIndex], leak.Carrier, amount);
        }

        return level with { Surface = surface.Select(cell => cell.Clamp()).ToArray() };
    }
}