using Hcs.Broker.Internal;
using Hcs.Service.Async.OrgRegistryCommon;

namespace Hcs.Broker.Api.Request.OrgRegistryCommon
{
    internal class ExportOrgRegistryRequest(Client client) : OrgRegistryCommonRequestBase(client)
    {
        private const int OGRN_LENGTH = 13;

        internal async Task<IEnumerable<exportOrgRegistryResultType>> ExecuteAsync(string ogrn, string kpp, CancellationToken token)
        {
            if (ogrn.Length != OGRN_LENGTH)
            {
                throw new System.ArgumentException($"The length of {ogrn} is incorrect");
            }

            var criteria = new exportOrgRegistryRequestSearchCriteria();
            if (!string.IsNullOrEmpty(kpp))
            {
                criteria.Items = [ogrn, kpp];
                criteria.ItemsElementName = [ItemsChoiceType3.OGRN, ItemsChoiceType3.KPP];
            }
            else
            {
                criteria.Items = [ogrn];
                criteria.ItemsElementName = [ItemsChoiceType3.OGRN];
            }

            // http://open-gkh.ru/OrganizationsRegistryCommon/exportOrgRegistryRequest.html
            var request = new exportOrgRegistryRequest
            {
                Id = Constants.SIGNED_XML_ELEMENT_ID,
                version = "10.0.2.1",
                SearchCriteria = [criteria]
            };

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

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