using MediatR;
using Microsoft.EntityFrameworkCore;
using System;
using System.Threading;
using System.Threading.Tasks;
using UserManagement.Common.UnitOfWork;
using UserManagement.Data.Dto;
using UserManagement.Domain;
using UserManagement.Helper;
using UserManagement.MediatR.Commands;
using UserManagement.Repository;

namespace UserManagement.MediatR.Handlers
{
    public class DeleteReminderCurrentUserCommandHandler : IRequestHandler<DeleteReminderCurrentUserCommand, ServiceResponse<bool>>
    {
        private readonly IReminderRepository _reminderRepository;
        private readonly IReminderUserRepository _reminderUserRepository;
        private readonly IUnitOfWork<UserContext> _uow;
        private readonly UserInfoToken _userInfoToken;

        public DeleteReminderCurrentUserCommandHandler(
            IReminderRepository reminderRepository,
            IUnitOfWork<UserContext> uow,
             IReminderUserRepository reminderUserRepository,
             UserInfoToken userInfoToken)
        {
            _reminderRepository = reminderRepository;
            _uow = uow;
            _reminderUserRepository = reminderUserRepository;
            _userInfoToken = userInfoToken;
        }

        public async Task<ServiceResponse<bool>> Handle(DeleteReminderCurrentUserCommand request, CancellationToken cancellationToken)
        {
            var reminder = await _reminderRepository.FindAsync(request.Id);
            if (reminder == null)
            {
                return ServiceResponse<bool>.Return404();
            }

            var reminserUser = await _reminderUserRepository.FindBy(c => c.ReminderId == request.Id && c.UserId == Guid.Parse(_userInfoToken.Id))
                                .FirstOrDefaultAsync();

            if (reminserUser != null)
            {
                _reminderUserRepository.Remove(reminserUser);
            }
            else
            {
                return ServiceResponse<bool>.Return404();
            }
            if (await _uow.SaveAsync() <= 0)
            {
                return ServiceResponse<bool>.Return500();
            }

            return ServiceResponse<bool>.ReturnSuccess();
        }
    }
}
