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

namespace Modules.User.Application.Commands;

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

public class SetUserInformationCommandHandler(UserContext userContext, IUserGateway userGateway) : IRequestHandler<SetUserInformationCommand, Unit>
{
    public async Task<Unit> Handle(SetUserInformationCommand 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.SetFirstName(request.FirstName);
        user.SetPatronymic(request.Patronymic);
        user.SetLastName(request.LastName);
        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;
    }
}