using System;
using System.Collections.Generic;
using System.Linq;
using EventsAppQuest.Web.Domain;

namespace EventsAppQuest.Web.Application
{
    /// <summary>
    /// Armazenamento em memória das comparações de snapshots por ciclo. Mock; sem persistência real.
    /// </summary>
    public static class SnapshotComparisonStore
    {
        private static readonly Dictionary<string, List<EventCycleSnapshotComparison>> ByCycleId = new Dictionary<string, List<EventCycleSnapshotComparison>>();
        private static readonly object Lock = new object();

        public static void AddComparison(EventCycleSnapshotComparison comparison)
        {
            if (comparison == null || string.IsNullOrEmpty(comparison.CycleId)) return;
            lock (Lock)
            {
                if (!ByCycleId.TryGetValue(comparison.CycleId, out var list))
                {
                    list = new List<EventCycleSnapshotComparison>();
                    ByCycleId[comparison.CycleId] = list;
                }
                list.Add(comparison);
            }
        }

        public static List<EventCycleSnapshotComparison> GetByCycleId(string cycleId)
        {
            if (string.IsNullOrEmpty(cycleId)) return new List<EventCycleSnapshotComparison>();
            lock (Lock)
            {
                if (!ByCycleId.TryGetValue(cycleId, out var list)) return new List<EventCycleSnapshotComparison>();
                return list.Where(c => c != null).OrderByDescending(c => c.ComparedAt).ToList();
            }
        }

        public static List<EventCycleSnapshotComparison> GetAll()
        {
            lock (Lock)
                return ByCycleId.Values.SelectMany(v => v).Where(c => c != null).OrderByDescending(c => c.ComparedAt).ToList();
        }

        public static void ClearCycle(string cycleId)
        {
            if (string.IsNullOrEmpty(cycleId)) return;
            lock (Lock)
                ByCycleId.Remove(cycleId);
        }

        public static void ClearAll()
        {
            lock (Lock)
                ByCycleId.Clear();
        }
    }
}

