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

namespace Indotalent.Features.Profile.Password.Cqrs;

public class UpdatePasswordRequest
{
    public string Id { get; set; } = string.Empty;
    public string CurrentPassword { get; set; } = string.Empty;
    public string NewPassword { get; set; } = string.Empty;
}

public class UpdatePasswordResponse
{
    public bool Success { get; set; }
    public string Message { get; set; } = string.Empty;
    public List<string>? Errors { get; set; }
}

public record UpdatePasswordCommand(UpdatePasswordRequest Data) : IRequest<UpdatePasswordResponse>;

public class UpdatePasswordHandler : IRequestHandler<UpdatePasswordCommand, UpdatePasswordResponse>
{
    private readonly UserManager<ApplicationUser> _userManager;

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

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

        var result = await _userManager.ChangePasswordAsync(user, request.Data.CurrentPassword, request.Data.NewPassword);

        if (result.Succeeded)
            return new UpdatePasswordResponse { Success = true };

        return new UpdatePasswordResponse
        {
            Success = false,
            Message = "Failed to update password",
            Errors = result.Errors.Select(x => x.Description).ToList()
        };
    }
}