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

namespace IamService.API.Application.Queries.Roles;

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

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

    public async Task<GetRolesQueryResult> Handle(GetRolesQuery request, CancellationToken cancellationToken)
    {
        _logger.LogInformation("Getting roles - Page: {Page}, Size: {Size}", request.PageNumber, request.PageSize);

        var query = _roleManager.Roles;

        var totalCount = await query.CountAsync(cancellationToken);

        var roles = await query
            .OrderBy(r => r.Name)
            .Skip((request.PageNumber - 1) * request.PageSize)
            .Take(request.PageSize)
            .Select(r => new RoleDto(
                r.Id,
                r.Name!,
                r.Description,
                r.IsSystemRole,
                r.CreatedAt))
            .ToListAsync(cancellationToken);

        return new GetRolesQueryResult(
            roles,
            totalCount,
            request.PageNumber,
            request.PageSize);
    }
}
