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 GetCounterpartiesQueryHandler : IRequestHandler<GetCounterpartiesQuery, ResponseModel<List<CounterpartyViewDto>>>
    {
        private readonly ILogger _logger;
        private readonly DsacContext _context;
        private readonly IMapper _mapper;

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

        public async Task<ResponseModel<List<CounterpartyViewDto>>> Handle(GetCounterpartiesQuery request, CancellationToken cancellationToken)
        {
            try
            {
                var res = await _context.Counterparties
                        .Where(x=>request.Ids == null || request.Ids.Contains(x.Id))
                        .Skip(request.Page * request.PageSize).Take(request.PageSize)
                        .ToListAsync();

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

                return new()
                {
                    StatusCode = System.Net.HttpStatusCode.BadRequest,
                    ErrorText = "Cannot get Counterparties by this request",
                };
            }
        }
    }
}
