using Indotalent.Data.Entities;
using MediatR;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.WebUtilities;
using System.Text;

namespace Indotalent.Features.Account.ResetPassword.Cqrs;

public class ResetPasswordRequest
{
    public string UserId { get; set; } = string.Empty;
    public string Code { get; set; } = string.Empty;
    public string NewPassword { get; set; } = string.Empty;
}

public class ResetPasswordResponse
{
    public string Message { get; set; } = string.Empty;
}

public record ResetPasswordCommand(ResetPasswordRequest Data) : IRequest<ResetPasswordResponse>;

public class ResetPasswordHandler : IRequestHandler<ResetPasswordCommand, ResetPasswordResponse>
{
    private readonly UserManager<ApplicationUser> _userManager;

    public ResetPasswordHandler(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }

    public async Task<ResetPasswordResponse> Handle(ResetPasswordCommand request, CancellationToken cancellationToken)
    {
        var user = await _userManager.FindByIdAsync(request.Data.UserId);
        if (user == null)
        {
            throw new Exception("User not found.");
        }

        var decodedCode = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(request.Data.Code));
        var result = await _userManager.ResetPasswordAsync(user, decodedCode, request.Data.NewPassword);

        if (!result.Succeeded)
        {
            var errors = result.Errors.Select(x => x.Description).ToList();
            throw new Exception(string.Join(", ", errors));
        }

        return new ResetPasswordResponse { Message = "Password has been reset successfully." };
    }
}