using MediatR;
using Modules.User.Application.Errors;
using Modules.User.Application.Gateways;
using Modules.User.Domain.Gateways;

namespace Modules.User.Application.Commands;

public class CreateUserCommand : IRequest<Guid>
{
    public string Email { get; set; } = default!;
    public string Password { get; set; } = default!;
    public string Nickname { get; set; } = default!;
}

//public class CreateUserCommandHandler(IUserGateway userGateway, IPasswordGateway passwordGateway, IPasswordHasher passwordHasher) : IRequestHandler<CreateUserCommand, Guid>
public class CreateUserCommandHandler(IUserGateway userGateway, IPasswordGateway passwordGateway) : IRequestHandler<CreateUserCommand, Guid>
{
    public async Task<Guid> Handle(CreateUserCommand request, CancellationToken cancellationToken)
    {
        //if (await userGateway.IsExists(request.Email)) throw new Exception("Account with the same eamil already exists");
        if (await userGateway.IsExists(request.Email)) throw new AccountException();
        var newUser = Domain.Entities.User.User.Create(request.Email, request.Password, passwordGateway, request.Nickname);

        var userId = await userGateway.CreateUser(new Models.Account
        {
            Email = newUser.Account.Email.Value,
            HashedPassword = newUser.Account.HashedPassword,
        }, new Models.User
        {
            NickName = newUser.NickName,
            FirstName = newUser.FirstName,
            Patronymic = newUser.Patronymic,
            LastName = newUser.LastName,
            //AvatarId = newUser.AvatarId,
            LanguageId = newUser.LanguageId,
        }, newUser.AvatarId);

        return userId;
    }
}