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

namespace adas_core.Domain.Models;

/// <summary>
/// Represents an action related to the location of a patient.
/// </summary>
/// <remarks>
/// This type encapsulates an operation or behavior associated with managing or interacting with a patient's location information.
/// </remarks>
public class PatientLocationAction
{
    public ActionsEnum.ResourceAction? Action { get; set; }

    public PatientLocation? Location { get; set; }


    /// <summary>
    /// Applies a collection of <see cref="PatientLocationAction"/> entries to produce the resulting set of <see cref="PatientLocation"/> records.
    /// </summary>
    /// <param name="actions">The list of patient location actions to apply. May be <c>null</c>.</param>
    /// <returns>The resulting <see cref="List{PatientLocation}"/> produced by applying the actions, or <c>null</c> if no locations are produced.</returns>
    public static List<PatientLocation>? Apply(List<PatientLocationAction>? actions)
    {
        return Apply(null, actions);
    }

    /// <summary>
    /// Applies a list of <see cref="PatientLocationAction"/> entries to a source list of <see cref="PatientLocation"/> objects, supporting add, delete, and update operations, and returns the resulting list or null when empty.
    /// </summary>
    /// <param name="source">The list of patient locations to mutate. If null, an empty list is used.</param>
    /// <param name="actions">The actions to apply to the source list. If null, no actions are applied; actions with a null <c>Location</c> are skipped.</param>
    /// <returns>The resulting list of <see cref="PatientLocation"/> after applying the actions, or null if the list is empty.</returns>
    public static List<PatientLocation>? Apply(List<PatientLocation>? source, List<PatientLocationAction>? actions)
    {
        source ??= [];
        (actions ?? []).ForEach(s =>
        {
            if (s.Location != null)
                switch (s.Action)
                {
                    case ActionsEnum.ResourceAction.Add:
                        if (!source.Contains(s.Location)) source.Add(s.Location);
                        break;
                    case ActionsEnum.ResourceAction.Delete:
                        if (source.Contains(s.Location)) source.Remove(s.Location);
                        break;

                    case ActionsEnum.ResourceAction.Update:
                        if (source.Contains(s.Location)) source[source.IndexOf(s.Location)] = s.Location;
                        else source.Add(s.Location);
                        break;
                }
        });

        return CollectionsUtils.NullIfEmpty(source);
    }
}