using System.Net;
using JShop.Core;
using JShop.Core.Repositories;
using JShop.Shared.Contracts.Identity;
using JShop.Shared.Results;
using MassTransit;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
namespace JShop.Application.Identity.Commands.RegisterUser;
public sealed class RegisterUserHandler : IConsumer<RegisterUserCommand>
{
private readonly IUsersRepository _usersRepository;
private readonly IPasswordHasher<User> _passwordHasher;
public RegisterUserHandler(IUsersRepository usersRepository, IPasswordHasher<User> passwordHasher)
{
_usersRepository = usersRepository;
_passwordHasher = passwordHasher;
}
public async Task Consume(ConsumeContext<RegisterUserCommand> context)
{
var normalizedEmail = context.Message.Email.ToUpper();
var usedEmail = await _usersRepository.AllUsers()
.FirstOrDefaultAsync(x => x.Email == normalizedEmail);
if (usedEmail is not null)
{
await context.RespondAsync(new Result(HttpStatusCode.Conflict, None.Instance));
return;
}
var user = new User
{
Email = normalizedEmail
};
user.PasswordHash = _passwordHasher.HashPassword(user, context.Message.Password);
await _usersRepository.AddUserAsync(user, context.CancellationToken);
await _usersRepository.SaveChangesAsync(context.CancellationToken);
await context.RespondAsync(new Result(HttpStatusCode.Created, None.Instance));
}
}