using Hcs.Broker.Api.Request.Adapter;
using Hcs.Broker.Internal;
using Hcs.Service.Async.Nsi;

namespace Hcs.Broker.Api.Request.Nsi
{
    internal class ExportDataProviderNsiItemRequest(Client client) : NsiRequestBase(client)
    {
        internal async Task<IEnumerable<NsiItemType>> ExecuteAsync(exportDataProviderNsiItemRequestRegistryNumber registryNumber, CancellationToken token)
        {
            // http://open-gkh.ru/Nsi/exportDataProviderNsiItemRequest.html
            var request = new exportDataProviderNsiItemRequest
            {
                Id = Constants.SIGNED_XML_ELEMENT_ID,
                version = "10.0.1.2",
                RegistryNumber = registryNumber
            };

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

            return result.Items.OfType<NsiItemType>();
        }

        internal async Task<string> SendAsync(exportDataProviderNsiItemRequestRegistryNumber registryNumber, CancellationToken token)
        {
            // http://open-gkh.ru/Nsi/exportDataProviderNsiItemRequest.html
            var request = new exportDataProviderNsiItemRequest
            {
                Id = Constants.SIGNED_XML_ELEMENT_ID,
                version = "10.0.1.2",
                RegistryNumber = registryNumber
            };

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

        internal async Task<RequestSingleResult<NsiItemType>> GetResultAsync(string messageGuid)
        {
            var result = await ExecuteGetResultAsync(messageGuid);
            if (result == null)
            {
                return RequestSingleResult<NsiItemType>.CreateNotReady();
            }

            var item = result.Items.FirstOrDefault();
            if (item is NsiItemType nsiItem)
            {
                return RequestSingleResult<NsiItemType>.CreateSuccessful(nsiItem);
            }
            else if (item is IErrorMessage errorMessage)
            {
                return RequestSingleResult<NsiItemType>.CreateFailed(errorMessage);
            }
            return RequestSingleResult<NsiItemType>.CreateFailed(null);
        }
    }
}
