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

namespace Modules.User.Application.Commands.UserInformation;

public class SetUserLanguageCommand : IRequest<Unit>
{
    public Guid? LanguageId { get; init; }
}

public class SetUserLanguageCommandHandler(UserContext userContext, IUserRepository userRepository,
    IUnitOfWork unitOfWork) : IRequestHandler<SetUserLanguageCommand, Unit>
{
    public async Task<Unit> Handle(SetUserLanguageCommand 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"

        var language = !request.LanguageId.HasValue ? null : Language.Create(request.LanguageId.Value);
        user.SetLanguage(language);
        await userRepository.SaveAsync(user, cancellationToken);
        await unitOfWork.SaveChangesAsync(cancellationToken);

        return Unit.Value;
    }
}