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

namespace EventsAppQuest.Web.Producer.Application
{
    /// <summary>
    /// Armazenamento em memória do estado de execução e updates por pedido (mock).
    /// </summary>
    public static class ExecutionTrackingStore
    {
        private static readonly Dictionary<string, ProducerExecutionStatusState> States = new Dictionary<string, ProducerExecutionStatusState>();
        private static readonly List<ProducerExecutionUpdate> Updates = new List<ProducerExecutionUpdate>();
        private static readonly object Lock = new object();

        public static ProducerExecutionStatusState GetOrCreateState(string orderId)
        {
            if (string.IsNullOrEmpty(orderId)) return null;
            lock (Lock)
            {
                if (States.TryGetValue(orderId, out var existing))
                    return existing;
                var state = new ProducerExecutionStatusState
                {
                    ProducerOrderId = orderId,
                    ExecutionStatus = ProducerExecutionStatus.NotStarted,
                    StartedAt = null,
                    LastUpdatedAt = null,
                    ProgressPercent = 0,
                    CurrentExecutionSummary = null,
                    HasIssues = false,
                    IsPaused = false,
                    IsCompleted = false,
                    CompletionSummary = null
                };
                States[orderId] = state;
                return state;
            }
        }

        public static void SetState(ProducerExecutionStatusState state)
        {
            if (state == null || string.IsNullOrEmpty(state.ProducerOrderId)) return;
            lock (Lock)
            {
                state.LastUpdatedAt = DateTime.UtcNow;
                States[state.ProducerOrderId] = state;
            }
        }

        public static ProducerExecutionUpdate AddUpdate(ProducerExecutionUpdate update)
        {
            if (update == null) return null;
            lock (Lock)
            {
                Updates.Add(update);
                return update;
            }
        }

        public static IReadOnlyList<ProducerExecutionUpdate> GetUpdates(string orderId, int maxCount = 20)
        {
            if (string.IsNullOrEmpty(orderId)) return new List<ProducerExecutionUpdate>();
            lock (Lock)
                return Updates.Where(u => u.ProducerOrderId == orderId).OrderByDescending(u => u.CreatedAt).Take(maxCount).ToList();
        }
    }
}
