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

namespace Hcs.Broker.Api.Request.NsiCommon
{
    internal class ExportNsiItemRequest(Client client) : NsiCommonRequestBase(client)
    {
        internal async Task<NsiItemType> ExecuteAsync(int registryNumber, ListGroup listGroup, CancellationToken token)
        {
            // http://open-gkh.ru/NsiCommon/exportNsiItemRequest.html
            var request = new exportNsiItemRequest
            {
                Id = Constants.SIGNED_XML_ELEMENT_ID,
                version = "10.0.1.2",
                RegistryNumber = registryNumber.ToString(),
                ListGroup = listGroup
            };

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

            return result.Item as NsiItemType;
        }

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

            return await SendAsync(request, async asyncClient =>
            {
                var response = await asyncClient.exportNsiItemAsync(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();
            }
            if (result.Item is NsiItemType nsiItem)
            {
                return RequestSingleResult<NsiItemType>.CreateSuccessful(nsiItem);
            }
            else if (result.Item is IErrorMessage errorMessage)
            {
                return RequestSingleResult<NsiItemType>.CreateFailed(errorMessage);
            }
            return RequestSingleResult<NsiItemType>.CreateFailed(null);
        }
    }
}
