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

namespace Modules.User.Application.Commands.UserInformation;

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

public class SetUserBirthDateCommandHandler(UserContext userContext, IUserRepository userRepository,
    IUnitOfWork unitOfWork) : IRequestHandler<SetUserBirthDateCommand, Unit>
{
    public async Task<Unit> Handle(SetUserBirthDateCommand 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.SetBirthDate(request.BirthDate);
        await userRepository.SaveAsync(user, cancellationToken);
        await unitOfWork.SaveChangesAsync(cancellationToken);

        return Unit.Value;
    }
}