using Hcs.Broker.Api.Payload.HouseManagement;
using Hcs.Broker.Api.Request.Exception;
using Hcs.Broker.Internal;
using Hcs.Service.Async.HouseManagement;

namespace Hcs.Broker.Api.Request.HouseManagement
{
    internal class ImportNotificationDataRequest(Client client) : HouseManagementRequestBase(client)
    {
        protected override bool CanBeRestarted => false;

        internal async Task<bool> ExecuteAsync(ImportNotificationDataPayload payload, CancellationToken token)
        {
            // TODO: Добавить проверку пейлоада

            var notification = new importNotificationRequestNotification()
            {
                TransportGUID = Guid.NewGuid().ToString(),
                Item = GetNotificationFromPayload(payload)
            };

            // http://open-gkh.ru/HouseManagement/importNotificationRequest.html
            var request = new importNotificationRequest
            {
                Id = Constants.SIGNED_XML_ELEMENT_ID,
                version = "13.2.2.0",
                notification = [notification]
            };

            var result = await SendAndWaitResultAsync(request, async asyncClient =>
            {
                var response = await asyncClient.importNotificationDataAsync(CreateRequestHeader(), request);
                return response.AckRequest.Ack;
            }, token);

            result.Items.OfType<ErrorMessageType>().ToList().ForEach(error =>
            {
                throw RemoteException.CreateNew(error.ErrorCode, error.Description);
            });

            var importResults = result.Items.OfType<getStateResultImportResult>();
            var commonResults = GetCommonResults(importResults);

            return true;
        }

        private importNotificationRequestNotificationCreate GetNotificationFromPayload(ImportNotificationDataPayload payload)
        {
            var notification = new importNotificationRequestNotificationCreate();

            if (!string.IsNullOrEmpty(payload.topic))
            {
                notification.Item = payload.topic;
            }
            else
            {
                notification.Item = payload.topicFromRegistry;
            }

            if (payload.isImportant)
            {
                notification.IsImportant = true;
                notification.IsImportantSpecified = true;
            }

            notification.content = payload.content;

            var items = new List<object>();
            var itemsElementName = new List<ItemsChoiceType29>();
            foreach (var tuple in payload.destinations)
            {
                items.Add(tuple.Item2);
                itemsElementName.Add(tuple.Item1);
            }
            notification.Items = [.. items];
            notification.ItemsElementName = [.. itemsElementName];

            if (payload.isNotLimit)
            {
                notification.Items1 = [true];
                notification.Items1ElementName = [Items1ChoiceType.IsNotLimit];
            }
            else
            {
                notification.Items1 = [payload.startDate.Value, payload.endDate.Value];
                notification.Items1ElementName = [Items1ChoiceType.StartDate, Items1ChoiceType.EndDate];
            }

            // TODO: Добавить добавление аттачмента

            if (payload.isShipOff)
            {
                notification.IsShipOff = true;
                notification.IsShipOffSpecified = true;
            }

            if (payload.isForPublishToMobileApp)
            {
                notification.IsForPublishToMobileApp = true;
                notification.IsForPublishToMobileAppSpecified = true;
            }

            notification.MobileAppData = payload.mobileAppData;

            return notification;
        }
    }
}
