using adas_core.Domain.Enums;
using adas_core.Domain.Utils;

namespace adas_core.Domain.Models;

/// <summary>
/// Represents a code action that encapsulates an operation or transformation to be performed on code.
/// </summary>
public class CodeAction
{
    public ActionsEnum.ResourceAction Action { get; set; }
    public required Code Code { get; set; }

    /// <summary>
    /// Applies a list of <see cref="CodeAction"/> items and returns the resulting <see cref="Code"/> list, using the default (null) context by delegating to the contextual overload.
    /// </summary>
    /// <param name="actions">The list of code actions to apply.</param>
    /// <returns>A <see cref="List{Code}"/> with the applied changes, or <c>null</c> if no codes are produced.</returns>
    public static List<Code>? Apply(List<CodeAction> actions)
        {
            return Apply(null, actions);
        }

    /// <summary>
    /// Applies a list of code actions to the source list, handling addition, deletion, and update operations while avoiding duplicates.
    /// Returns null if the resulting source list is empty.
    /// </summary>
    /// <param name="source">The list of codes to modify. If null, an empty list is used as the starting point.</param>
    /// <param name="actions">The list of code actions to apply. If null, the source list is returned unchanged.</param>
    /// <returns>The modified list of codes, or null if the list is empty after applying the actions.</returns>
    public static List<Code>? Apply(List<Code>? source, List<CodeAction>? actions)
        {
            source ??= [];
            (actions ?? []).ForEach(s =>
            {
                switch (s.Action)
                {
                    case ActionsEnum.ResourceAction.Add:
                        if (!source.Contains(s.Code)) source.Add(s.Code);
                        break;
                    case ActionsEnum.ResourceAction.Delete:
                        if (source.Contains(s.Code)) source.Remove(s.Code);
                        break;
    
                    case ActionsEnum.ResourceAction.Update:
                        if (source.Contains(s.Code)) source[source.IndexOf(s.Code)] = s.Code;
                        else source.Add(s.Code);
                        break;
                }
            });
            return CollectionsUtils.NullIfEmpty(source);
        }
}