﻿using FluentValidation;
using MediatR;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using THEBooks.Domain.Core.Entities;
using THEBooks.Domain.UserContext.Queries.Requests;
using THEBooks.Domain.UserContext.Queries.Responses;
using THEBooks.Domain.UserContext.Repositories;

namespace THEBooks.Domain.UserContext.Handlers.Queries
{
    public sealed class SearchUserByIdQueryHandler : IRequestHandler<SearchUserByIdQueryRequest, HandlerResult<SearchUserByIdQueryResponse>>
    {
        public SearchUserByIdQueryHandler(IUserRepository userRepository, IValidator<SearchUserByIdQueryRequest> validator)
        {
            this.userRepository = userRepository;
            this.validator = validator;
        }

        private readonly IUserRepository userRepository;
        private readonly IValidator<SearchUserByIdQueryRequest> validator;

        public async Task<HandlerResult<SearchUserByIdQueryResponse>> Handle(SearchUserByIdQueryRequest queryRequest, CancellationToken cancellationToken)
        {
            var validationResult = await validator.ValidateAsync(queryRequest, cancellationToken);

            if (validationResult.IsValid is false)
                return new HandlerResult<SearchUserByIdQueryResponse>(HttpStatusCode.BadRequest, validationResult.Errors);

            var user = await userRepository.SearchUserByIdAsync(queryRequest);

            if (user is null)
                return new HandlerResult<SearchUserByIdQueryResponse>(HttpStatusCode.NotFound, "Id doesn't exists");

            return new HandlerResult<SearchUserByIdQueryResponse>(HttpStatusCode.OK, user);
        }
    }
}
