using AutoMapper;
using DSaC_second.Database;
using DSaC_second.Logic.Handlers.Commands;
using DSaC_second.Models.DTOs;
using DSaC_second.Models.Internal;
using DSaC_second.Models.Internal.Queries;
using MediatR;
using PIHelperSh.Configuration.Attributes;
using RestSharp;

namespace DSaC_second.Logic.Handlers.Queries
{
    [TrackedType]
    public class GetConunterpartyQueryHandler : IRequestHandler<GetConunterpartyQuery, ResponseModel<CounterpartyViewDto>>
    {
        private readonly ILogger _logger;
        private readonly DsacContext _context;
        private readonly IMapper _mapper;
        private readonly RestClient _restClient;

        [Constant(BlockName = "FirstService")]
        private static string BaseUrl;

        [Constant(BlockName = "FirstService")]
        private static string GetCounterpartyPostfix;

        public GetConunterpartyQueryHandler(ILogger<GetConunterpartyQueryHandler> logger, DsacContext context, IMapper mapper)
        {
            _logger = logger;
            _context = context;
            _mapper = mapper;
            _restClient = new RestClient(BaseUrl);
        }

        ~GetConunterpartyQueryHandler()
        {
            _restClient.Dispose();
        }

        public async Task<ResponseModel<CounterpartyViewDto>> Handle(GetConunterpartyQuery request, CancellationToken cancellationToken)
        {
            try
            {
                var rq = new RestRequest($"{GetCounterpartyPostfix}/{request.Id.ToString()}");

                var res = await _restClient.ExecuteAsync<CounterpartyViewDto>(rq, cancellationToken:cancellationToken);

                if (res.IsSuccessful)
                    return new()
                    {
                        Value = res.Data
                    };

                return new()
                {
                    StatusCode = res.StatusCode,
                    ErrorText = res.ErrorMessage,
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error on getting record from first service");

                return new()
                {
                    StatusCode = System.Net.HttpStatusCode.NotFound,
                    ErrorText = "Cannot get cpty from first service",
                };
            }
        }
    }
}
