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

namespace IamService.API.Application.Queries.Roles;

/// <summary>
/// EN: Handler for GetRolePermissionsQuery — reads permission claims from role_claims table.
/// VI: Handler cho GetRolePermissionsQuery — đọc permission claims từ bảng role_claims.
/// </summary>
public class GetRolePermissionsQueryHandler : IRequestHandler<GetRolePermissionsQuery, GetRolePermissionsQueryResult?>
{
    private readonly RoleManager<ApplicationRole> _roleManager;
    private readonly IamServiceContext _dbContext;

    public GetRolePermissionsQueryHandler(
        RoleManager<ApplicationRole> roleManager,
        IamServiceContext dbContext)
    {
        _roleManager = roleManager;
        _dbContext = dbContext;
    }

    public async Task<GetRolePermissionsQueryResult?> Handle(
        GetRolePermissionsQuery request, CancellationToken cancellationToken)
    {
        var role = await _roleManager.FindByIdAsync(request.RoleId.ToString());
        if (role == null) return null;

        var permissions = await _dbContext.RoleClaims
            .Where(rc => rc.RoleId == request.RoleId && rc.ClaimType == "permission")
            .Select(rc => rc.ClaimValue!)
            .ToListAsync(cancellationToken);

        return new GetRolePermissionsQueryResult(
            role.Id,
            role.Name!,
            role.IsSystemRole,
            permissions);
    }
}
