using MediatR;
using TakeoutSaaS.Application.Identity.Contracts;
using TakeoutSaaS.Application.Identity.Queries;
using TakeoutSaaS.Domain.Identity.Enums;
using TakeoutSaaS.Domain.Identity.Repositories;
using TakeoutSaaS.Shared.Abstractions.Results;

namespace TakeoutSaaS.Application.Identity.Handlers;

/// <summary>
/// 获取租户角色列表查询处理器。
/// </summary>
public sealed class ListTenantRolesQueryHandler(IRoleRepository roleRepository)
    : IRequestHandler<ListTenantRolesQuery, PagedResult<RoleDto>>
{
    /// <inheritdoc />
    public async Task<PagedResult<RoleDto>> Handle(ListTenantRolesQuery request, CancellationToken cancellationToken)
    {
        // 1. 查询租户下所有角色
        var roles = await roleRepository.SearchAsync(PortalType.Tenant, request.TenantId, request.Keyword, cancellationToken);

        // 2. 计算分页参数
        var totalCount = roles.Count;
        var page = Math.Max(1, request.Page);
        var pageSize = Math.Clamp(request.PageSize, 1, 100);

        // 3. 应用分页
        var pagedRoles = roles
            .OrderBy(r => r.Code)
            .Skip((page - 1) * pageSize)
            .Take(pageSize)
            .ToArray();

        // 4. 映射 DTO
        var dtos = pagedRoles.Select(role => new RoleDto
        {
            Portal = role.Portal,
            Id = role.Id,
            TenantId = role.TenantId,
            Code = role.Code,
            Name = role.Name,
            Description = role.Description
        }).ToArray();

        // 5. 返回分页结果
        return new PagedResult<RoleDto>(dtos, page, pageSize, totalCount);
    }
}
