using AutoMapper;
using Diligent.WebAPI.Business.Interfaces;
using Diligent.WebAPI.Business.Services;
using Diligent.WebAPI.Host.Mediator.Request.Commands;
using MediatR;

namespace Diligent.WebAPI.Host.Mediator.Request.Handlers
{
    public class CreateRequestHandler : IRequestHandler<CreateRequestCommand, Data.Entities.Request>
    {
        private readonly IMapper _mapper;
        private readonly IRequestRepository _requestService;

        public CreateRequestHandler(IMapper mapper, IRequestRepository requestService)
        {
            _mapper = mapper;
            _requestService = requestService;
        }

        public async Task<Data.Entities.Request> Handle(CreateRequestCommand request, CancellationToken cancellationToken)
        {
            var req = request.Request;

            if (req == null)
                throw new BadHttpRequestException("Resource object cannot be null.");
            
            var createdRequest = _mapper.Map<Data.Entities.Request>(req);
            await _requestService.CreateAsync(createdRequest);

            return createdRequest;
        }
    }
}
