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

namespace Modules.User.Application.Commands;

public class SetUserBirthDateCommand : IRequest<Unit>
{
    public DateOnly? BirthDate { get; set; }
}

public class SetUserBirthDateCommandHandler(UserContext userContext, IUserGateway userGateway) : IRequestHandler<SetUserBirthDateCommand, Unit>
{
    public async Task<Unit> Handle(SetUserBirthDateCommand 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.SetBirthDate(request.BirthDate);
        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;
    }
}