using AutoMapper;
using Diligent.WebAPI.Business.Interfaces;
using Diligent.WebAPI.Data.Entities;
using Diligent.WebAPI.Host.DTOs.Customer;
using Diligent.WebAPI.Host.Mediator.Authentication.Commands;
using MediatR;
using Microsoft.AspNetCore.Identity;

namespace Diligent.WebAPI.Host.Mediator.Authentication.Handlers
{
    public class RegisterUserHandler : IRequestHandler<RegisterUserCommand, CustomerReadDTO>
    {
        private readonly UserManager<Customer> _customerManager;
        private readonly IAuthenticationService _authenticationService;
        private readonly IMapper _mapper;

        public RegisterUserHandler(UserManager<Customer> customerManager,IAuthenticationService authenticationService,
            IMapper mapper)
        {
            _customerManager = customerManager;
            _authenticationService = authenticationService;
            _mapper = mapper;
        }
        public async Task<CustomerReadDTO> Handle(RegisterUserCommand request, CancellationToken cancellationToken)
        {
            var customerCreateDTO = request.CustomerCreateDTO;
            Customer customer = new()
            {
                FirstName = customerCreateDTO.FirstName,
                LastName = customerCreateDTO.LastName,
                Email = customerCreateDTO.Email,
                UserName = customerCreateDTO.Username
            };

            var result = await _customerManager.CreateAsync(customer, customerCreateDTO.Password);
            await _customerManager.AddToRoleAsync(customer, "Support");
            await _authenticationService.ValidateCustomer(customer.UserName, customerCreateDTO.Password);
            var customerReadDTO = _mapper.Map<CustomerReadDTO>(customer);
            customerReadDTO.Token = await _authenticationService.GenerateToken();
            customerReadDTO.Roles = (List<string>)await _customerManager.GetRolesAsync(customer);

            return customerReadDTO;
        }
    }
}
