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

namespace IamService.API.Application.Queries.Roles;

/// <summary>
/// EN: Handler for GetRoleByIdQuery.
/// VI: Handler cho GetRoleByIdQuery.
/// </summary>
public class GetRoleByIdQueryHandler : IRequestHandler<GetRoleByIdQuery, RoleDto?>
{
    private readonly RoleManager<ApplicationRole> _roleManager;
    private readonly ILogger<GetRoleByIdQueryHandler> _logger;

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

    public async Task<RoleDto?> Handle(GetRoleByIdQuery request, CancellationToken cancellationToken)
    {
        _logger.LogInformation("Getting role by ID: {RoleId}", request.RoleId);

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

        if (role == null)
        {
            _logger.LogWarning("Role not found: {RoleId}", request.RoleId);
            return null;
        }

        return new RoleDto(
            role.Id,
            role.Name!,
            role.Description,
            role.IsSystemRole,
            role.CreatedAt);
    }
}
