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

namespace IamService.API.Application.Commands.Roles;

/// <summary>
/// EN: Handler for DeleteRoleCommand.
/// VI: Handler cho DeleteRoleCommand.
/// </summary>
public class DeleteRoleCommandHandler : IRequestHandler<DeleteRoleCommand, bool>
{
    private readonly RoleManager<ApplicationRole> _roleManager;
    private readonly ILogger<DeleteRoleCommandHandler> _logger;

    public DeleteRoleCommandHandler(
        RoleManager<ApplicationRole> roleManager,
        ILogger<DeleteRoleCommandHandler> logger)
    {
        _roleManager = roleManager;
        _logger = logger;
    }

    public async Task<bool> Handle(DeleteRoleCommand request, CancellationToken cancellationToken)
    {
        _logger.LogInformation("Deleting role: {RoleId}", request.RoleId);

        var role = await _roleManager.FindByIdAsync(request.RoleId.ToString());

        if (role == null)
        {
            _logger.LogWarning("Role not found: {RoleId}", request.RoleId);
            throw new DomainException($"Role with ID {request.RoleId} not found.");
        }

        // EN: Check if role is a system role
        // VI: Kiểm tra role có phải system role không
        if (role.IsSystemRole)
        {
            _logger.LogWarning("Cannot delete system role: {RoleId}", request.RoleId);
            throw new DomainException("Cannot delete system-defined roles.");
        }

        var result = await _roleManager.DeleteAsync(role);

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

        _logger.LogInformation("Role {RoleId} deleted successfully", request.RoleId);

        return true;
    }
}
