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

namespace IamService.API.Application.Commands.Users;

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

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

    public async Task<DeleteUserCommandResult> Handle(DeleteUserCommand request, CancellationToken cancellationToken)
    {
        _logger.LogInformation("Deleting 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: Soft delete - deactivate the user instead of hard delete
        // VI: Soft delete - deactivate user thay vì xóa hoàn toàn
        user.Disable();

        var updateResult = await _userManager.UpdateAsync(user);

        if (!updateResult.Succeeded)
        {
            var errors = string.Join(", ", updateResult.Errors.Select(e => e.Description));
            _logger.LogError("Failed to delete user {UserId}: {Errors}", request.UserId, errors);
            throw new DomainException($"Failed to delete user: {errors}");
        }

        _logger.LogInformation("User {UserId} deleted (deactivated) successfully", request.UserId);

        return new DeleteUserCommandResult(true, $"User {request.UserId} has been deactivated successfully.");
    }
}
