using AutoMapper;
using DSaC.Database;
using DSaC.Models.DTOs;
using DSaC.Models.Internal;
using DSaC.Models.Internal.Queries;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace DSaC.Logic.Handlers.Queries
{
    public class GetCounterpartyQueryHandler: IRequestHandler<GetCounterpartyQuery, ResponseModel<CounterpartyViewDto>>
    {
        private readonly ILogger _logger;
        private readonly DsacContext _context;
        private readonly IMapper _mapper;

        public GetCounterpartyQueryHandler(ILogger<GetCounterpartyQueryHandler> logger, DsacContext context, IMapper mapper)
        {
            _logger = logger;
            _context = context;
            _mapper = mapper;
        }

        public async Task<ResponseModel<CounterpartyViewDto>> Handle(GetCounterpartyQuery request, CancellationToken cancellationToken)
        {
            try
            {
                var res = await _context.Counterparties.FirstOrDefaultAsync(x=>x.Id == request.Id);

                if (res == null)
                    return new()
                    {
                        StatusCode = System.Net.HttpStatusCode.NotFound,
                        ErrorText = "Counterparty with this ID does not exsist",
                    };

                return new()
                {
                    Value = _mapper.Map<CounterpartyViewDto>(res),
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error on getting record");

                return new()
                {
                    StatusCode = System.Net.HttpStatusCode.NotFound,
                    ErrorText = "Cannot get Counterparty by id",
                };
            }
        }
    }
}
