using Indotalent.Data.Entities;
using MediatR;
using Microsoft.AspNetCore.Identity;

namespace Indotalent.Features.Setting.SystemUser.Cqrs;

public class ChangePasswordRequest
{
    public string UserId { get; set; } = string.Empty;
    public string NewPassword { get; set; } = string.Empty;
    public string ConfirmPassword { get; set; } = string.Empty;
}

public class ChangePasswordResponse
{
    public bool IsSuccess { get; set; }
    public string Message { get; set; } = string.Empty;
}



public record ChangePasswordCommand(ChangePasswordRequest Data) : IRequest<ChangePasswordResponse>;

public class ChangePasswordHandler : IRequestHandler<ChangePasswordCommand, ChangePasswordResponse>
{
    private readonly UserManager<ApplicationUser> _userManager;

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

    public async Task<ChangePasswordResponse> Handle(ChangePasswordCommand request, CancellationToken cancellationToken)
    {
        var user = await _userManager.FindByIdAsync(request.Data.UserId);
        if (user == null) return new ChangePasswordResponse { IsSuccess = false, Message = "User not found" };

        var token = await _userManager.GeneratePasswordResetTokenAsync(user);
        var result = await _userManager.ResetPasswordAsync(user, token, request.Data.NewPassword);

        if (result.Succeeded)
        {
            return new ChangePasswordResponse { IsSuccess = true, Message = "Password has been changed successfully" };
        }

        return new ChangePasswordResponse
        {
            IsSuccess = false,
            Message = string.Join(", ", result.Errors.Select(e => e.Description))
        };
    }
}