namespace KArtSell.Modules.SignalEngine.Domain;

public sealed class SellPolicyChain(IEnumerable<ISellPolicy> policies)
{
    private readonly ISellPolicy[] _policies = policies
        .OrderByDescending(x => x.Priority)
        .ThenBy(x => x.PolicyId, StringComparer.Ordinal)
        .ToArray();

    public SellDecision Evaluate(SellDecisionInput input)
    {
        input.EnsureValid();
        var trace = new List<PolicyTraceEntry>(_policies.Length);

        foreach (var policy in _policies)
        {
            var result = policy.Evaluate(input);
            trace.Add(result.Trace);
            if (result.Decision is not null)
            {
                return result.Decision with { PolicyTrace = trace.AsReadOnly() };
            }
        }

        return SellDecision.Hold(input, trace.AsReadOnly());
    }
}
