using MediatR;
using Microsoft.AspNetCore.Identity;
using IamService.Domain.AggregatesModel.UserAggregate;
using IamService.Domain.Exceptions;

namespace IamService.API.Application.Commands.Auth;

/// <summary>
/// EN: Handler for ChangePasswordCommand.
/// VI: Handler cho ChangePasswordCommand.
/// </summary>
public class ChangePasswordCommandHandler : IRequestHandler<ChangePasswordCommand, ChangePasswordCommandResult>
{
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly ILogger<ChangePasswordCommandHandler> _logger;

    public ChangePasswordCommandHandler(
        UserManager<ApplicationUser> userManager,
        ILogger<ChangePasswordCommandHandler> logger)
    {
        _userManager = userManager;
        _logger = logger;
    }

    public async Task<ChangePasswordCommandResult> Handle(ChangePasswordCommand request, CancellationToken cancellationToken)
    {
        _logger.LogInformation("Changing password for user: {UserId}", request.UserId);

        var user = await _userManager.FindByIdAsync(request.UserId.ToString());

        if (user == null)
        {
            _logger.LogWarning("User not found: {UserId}", request.UserId);
            throw new DomainException($"User with ID {request.UserId} not found.");
        }

        // EN: Validate current password and change to new password
        // VI: Xác thực mật khẩu hiện tại và đổi sang mật khẩu mới
        var result = await _userManager.ChangePasswordAsync(user, request.CurrentPassword, request.NewPassword);

        if (!result.Succeeded)
        {
            var errors = string.Join(", ", result.Errors.Select(e => e.Description));
            _logger.LogWarning("Failed to change password for user {UserId}: {Errors}", request.UserId, errors);
            return new ChangePasswordCommandResult(false, $"Failed to change password: {errors}");
        }

        _logger.LogInformation("Password changed successfully for user {UserId}", request.UserId);

        return new ChangePasswordCommandResult(true, "Password changed successfully.");
    }
}
