using ApiTerceiroSimulador.Code.Integration.Models;
using ApiTerceiroSimulador.Models.Integration.v1;

namespace ApiTerceiroSimulador.Code.Integration
{
    public class IntegrationService
    {
        //private static DateTime lastcreation = DateTime.MinValue;
        private static readonly List<IntegrationItem> _items = [];
        private static readonly List<NewEventsResponse> _events = [];

        //public static bool AutoGenerateOrders { get; set; } = false;

        private IntegrationItem CreateOrderInternal(OrderCreationSettings settings)
        {
            IntegrationItem novoitem;
            NewEventsResponse evento;

            evento = Creator.CreateEvent(settings);
            novoitem = Creator.CreateItem(settings);

            _events.Add(evento);
            _items.Add(novoitem);

            return novoitem;
        }

        public Dictionary<string, string> ListEventDs()
        {
            Dictionary<string, string> result = _events
                .ToDictionary(r => r.id, r => r.code);

            return result;
        }

        //public IEnumerable<NewEventsResponse> GetPendingEvents()
        //{
        //    const int INTERVALO_MINIMO = 1;
        //    const int ITERACOES = 1;

        //    OrderCreationSettings settings;

        //    TimeSpan ts = DateTime.Now - lastcreation;

        //    bool existe = _items
        //            .Where(r =>
        //                r.ConfirmedAt == null &&
        //                r.CancelledAt == null
        //            )
        //            .Any();

        //    // Criar os pedidos novos a cada 5 minutos para dar tempo de fazer os testes
        //    if (AutoGenerateOrders && ts.TotalMinutes >= INTERVALO_MINIMO)
        //    {
        //        // Criar novos eventos para a próxima requisição
        //        if (existe == false)
        //        {
        //            bool createunmapped = false;

        //            for (int i = 1; i <= ITERACOES; i++)
        //            {
        //                // Criar um item não mapeado na última iteração
        //                createunmapped = (i == ITERACOES - 1);

        //                settings = Creator.CreateSettings();
        //                settings.CreateUnmapped = createunmapped;
        //                settings.OrderType = OrderTypeOptions.Delivery;

        //                CreateOrderInternal(settings);
        //            }

        //            lastcreation = DateTime.Now;
        //        }
        //    }

        //    return _events;
        //}

        public IEnumerable<NewEventsResponse> GetPendingEvents()
        {
            return _events;
        }

        public IEnumerable<string> ListOrderIDs()
        {
            IEnumerable<string> result = _items
                .Select(r => r.OrderDetail.id)
                .ToList();

            return result;
        }

        public OrderDetailsResponse? GetOrderDetails(string orderId)
        {
            OrderDetailsResponse? result = _items
                .Where(r => r.OrderDetail.id == orderId)
                .Select(r => r.OrderDetail)
                .FirstOrDefault();

            return result;
        }

        public bool ConfirmOrder(string orderId, string status, string? description)
        {
            bool result = false;
            IntegrationItem? item = null;

            if (_items.Any() == false)
                return result;

            try
            {
                item = _items
                    .Where(r => r.OrderDetail.id == orderId)
                    .FirstOrDefault();

                if (item == null)
                    return result;

                if (status == StatusConfirmacao.Confirmed)
                {
                    item.ConfirmedAt = DateTime.Now;
                }
                else if (status == StatusConfirmacao.Cancelled)
                {
                    item.CancelledAt = DateTime.Now;
                    item.CancelationReason = description ?? "ND";
                }
                result = true;
            }
            catch (Exception)
            {

            }

            return result;
        }

        public IntegrationItem CreateOrder(CreateOrderOptions options)
        {
            OrderCreationSettings settings = Creator.CreateSettings();
            settings.CreateUnmapped = options.CreateUnmappedTestItem;

            if (options.IndoorTableNumer > 0)
            {
                settings.OrderType = OrderTypeOptions.Indoor;
                settings.IndoorTableNumer = options.IndoorTableNumer;
            }
            
            IntegrationItem novoitem = CreateOrderInternal(settings);

            return novoitem;
        }

        public NewEventsResponse CreateEvent(EventCreationSettings settings)
        {
            NewEventsResponse evento = Creator.CreateEvent(settings);

            _events.Add(evento);

            return evento;
        }

        public void RemoveEventByType(string orderId, string fullCode)
        {
            List<NewEventsResponse> eventos = _events
                .Where(r =>
                    r.orderId == orderId &&
                    r.fullCode == fullCode
                )
                .ToList();

            foreach (NewEventsResponse evento in eventos)
            {
                _events.Remove(evento);
            }
        }
    }
}
