using ReactorMaintenance.Simulation;

namespace ReactorMaintenance.Simulation.Effects;

public sealed class CellIntegrityEffect : ISimulationEffect
{
    public CellState Apply(CellState cell)
    {
        var integrity = cell.Integrity;
        var hazards = cell.Hazards;

        if (cell is { HasPipe: true } && cell.Pressure > Balancing.Current.OverpressureThreshold)
            integrity -= cell.Pressure - Balancing.Current.OverpressureThreshold;

        if (hazards.Heat >= Balancing.Current.HeatIntegrityDamageThreshold || hazards.Fire)
        {
            integrity -= cell.HasPipe ? Balancing.Current.PipeFireIntegrityDamage : Balancing.Current.MinHazardValue;
            hazards = hazards with { Stability = hazards.Stability - Balancing.Current.FireStabilityDamage };
        }

        cell = cell with {
            Integrity = Rules.Clamp(integrity),
            Hazards = hazards.Clamp()
        };

        if (integrity > Balancing.Current.MinHazardValue || !cell.HasPipe)
            return cell;

        return cell with {
            LeakRate = Math.Max(cell.LeakRate, Balancing.Current.BurstLeakRate),
            Flow = Balancing.Current.BrokenPipeFlow,
            PipeOpen = false
        };
    }
}