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

namespace Diligent.WebAPI.Host.Mediator.Request.Handlers
{
    public class AcceptCustomerRequestHandler : IRequestHandler<AcceptCustomerRequestCommand, string?>
    {
        private readonly IRequestRepository _requestRepository;
        private readonly RoomService _roomService;

        public AcceptCustomerRequestHandler(RoomService roomService, IRequestRepository requestRepository)
        {
            _roomService = roomService;
            _requestRepository = requestRepository;
        }
        public async Task<string?> Handle(AcceptCustomerRequestCommand request, CancellationToken cancellationToken)
        {
            var result1 = await _roomService.AddCustomerToRoom(request.CustomerId, request.RoomId);

            if (!result1)
                throw new NotFoundException($"Room with id={request.RoomId} doesn't exist");

            var req = await _requestRepository.FindRequestAsync(request.CustomerId, request.RoomId);

            if (req == null)
                throw new NotFoundException("Request are not found");

            await _requestRepository.RemoveAsync(req.Id);

            return req.Id;
        }
    }
}
