using Baya.Application.Contracts.Common;
using Baya.Application.Contracts.Identity;
using Baya.Application.Models.Common;
using Mediator;

namespace Baya.Application.Features.Users.Queries.TokenRequest;

public class UserTokenRequestQueryHandler(
    IAppUserManager userManager,
    ISmsSender smsSender)
    : IRequestHandler<UserTokenRequestQuery, OperationResult<UserTokenRequestQueryResponse>>
{


    public async ValueTask<OperationResult<UserTokenRequestQueryResponse>> Handle(UserTokenRequestQuery request, CancellationToken cancellationToken)
    {
        var user = await userManager.GetUserByPhoneNumber(request.UserPhoneNumber);

        if(user is null)
            return OperationResult<UserTokenRequestQueryResponse>.NotFoundResult("User Not found");

        var code = user.PhoneNumberConfirmed? await userManager.GenerateOtpCode(user) : await userManager.GeneratePhoneNumberConfirmationToken(user,user.PhoneNumber);

        await smsSender.SendOtpAsync(user.PhoneNumber, code, cancellationToken);

        return OperationResult<UserTokenRequestQueryResponse>.SuccessResult(new UserTokenRequestQueryResponse {UserKey = user.GeneratedCode});
    }
}