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

namespace Modules.User.Application.Commands.UserInformation;

public class SetUserNameCommand : IRequest<Unit>
{
    public string? FirstName { get; init; }
    public string? Patronymic { get; init; }
    public string? LastName { get; init; }
}

public class SetUserNameCommandHandler(UserContext userContext, IUserRepository userRepository,
    IUnitOfWork unitOfWork) : IRequestHandler<SetUserNameCommand, Unit>
{
    public async Task<Unit> Handle(SetUserNameCommand request, CancellationToken cancellationToken)
    {
        var accountId = userContext.GetAccountId();
        if (!accountId.HasValue) return Unit.Value;
        //TODO: if (!accountId.HasValue) throw new UnauthorizedAccessException("AccountId not found");
        
        var user = await userRepository.GetByAccountIdAsync(accountId.Value, cancellationToken);
        if (user == null) return Unit.Value;
        //TODO: if (user == null) throw new UserNotFoundException(); //"User not found"

        user.SetName(request.FirstName, request.Patronymic, request.LastName);
        await userRepository.SaveAsync(user, cancellationToken);
        await unitOfWork.SaveChangesAsync(cancellationToken);

        return Unit.Value;
    }
}