using MediatR;
using Modules.Media.Api.Commands;
using Modules.User.Application.Gateways;

namespace Modules.User.Application.Commands;

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

public class SetUserLanguageCommandHandler(UserContext userContext, IUserGateway userGateway) : IRequestHandler<SetUserLanguageCommand, Unit>
{
    public async Task<Unit> Handle(SetUserLanguageCommand request, CancellationToken cancellationToken)
    {
        var userInfo = await userContext.GetUserInfo(cancellationToken);
        if (userInfo?.AccountId == null) throw new Exception("User not found");
        var user = await userGateway.Get(userInfo.AccountId.Value) ?? throw new Exception("User was not found");

        user.SetLanguageId(request.LanguageId);
        await userGateway.UpdateUser(user.Id, new Models.User
        {
            NickName = user.NickName,
            FirstName = user.FirstName,
            Patronymic = user.Patronymic,
            LastName = user.LastName,
            BirthDate = user.BirthDate,
            LanguageId = user.LanguageId,
        }, user.AvatarId);

        return Unit.Value;
    }
}