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

namespace EventsAppQuest.Web.Application
{
    /// <summary>
    /// Armazenamento em memória de snapshots executivos por ciclo. Mock; sem persistência real.
    /// </summary>
    public static class ExecutiveSnapshotsStore
    {
        private static readonly Dictionary<string, List<EventCycleExecutiveSnapshot>> ByCycleId = new Dictionary<string, List<EventCycleExecutiveSnapshot>>();
        private static readonly object Lock = new object();
        private static int _counter;

        public static string AddSnapshot(EventCycleExecutiveSnapshot snapshot)
        {
            if (snapshot == null || string.IsNullOrEmpty(snapshot.CycleId)) return null;
            lock (Lock)
            {
                _counter++;
                var now = DateTime.UtcNow;
                snapshot.SnapshotId ??= $"Snap_{snapshot.CycleId}_{_counter}_{now.Ticks}";
                snapshot.CapturedAt ??= now;
                if (!ByCycleId.TryGetValue(snapshot.CycleId, out var list))
                {
                    list = new List<EventCycleExecutiveSnapshot>();
                    ByCycleId[snapshot.CycleId] = list;
                }
                list.Add(snapshot);
                return snapshot.SnapshotId;
            }
        }

        public static void RemoveSnapshot(string cycleId, string snapshotId)
        {
            if (string.IsNullOrEmpty(cycleId) || string.IsNullOrEmpty(snapshotId)) return;
            lock (Lock)
            {
                if (!ByCycleId.TryGetValue(cycleId, out var list)) return;
                list.RemoveAll(s => s != null && s.SnapshotId == snapshotId);
                if (list.Count == 0)
                    ByCycleId.Remove(cycleId);
            }
        }

        public static List<EventCycleExecutiveSnapshot> GetSnapshots(string cycleId)
        {
            if (string.IsNullOrEmpty(cycleId)) return new List<EventCycleExecutiveSnapshot>();
            lock (Lock)
            {
                if (!ByCycleId.TryGetValue(cycleId, out var list)) return new List<EventCycleExecutiveSnapshot>();
                return list.Where(s => s != null).OrderByDescending(s => s.CapturedAt).ToList();
            }
        }

        public static List<EventCycleExecutiveSnapshot> GetAllSnapshots()
        {
            lock (Lock)
            {
                return ByCycleId.Values.SelectMany(v => v).Where(s => s != null).OrderByDescending(s => s.CapturedAt).ToList();
            }
        }

        public static int GetTotalCount()
        {
            lock (Lock)
                return ByCycleId.Values.Sum(v => v?.Count ?? 0);
        }
    }
}

