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

namespace DSaC_second.Logic.Handlers.Queries
{
    public class GetContractsQueryHandler : IRequestHandler<GetContractsQuery, ResponseModel<List<ContractViewDto>>>
    {
        private readonly ILogger _logger;
        private readonly DsacContext _context;
        private readonly IMapper _mapper;

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

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

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

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