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

namespace TakeoutSaaS.Application.Identity.Handlers;

/// <summary>
/// 角色分页查询处理器。
/// </summary>
public sealed class SearchRolesQueryHandler(
    IRoleRepository roleRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<SearchRolesQuery, PagedResult<RoleDto>>
{
    /// <summary>
    /// 执行角色分页查询。
    /// </summary>
    /// <param name="request">查询参数。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>分页结果。</returns>
    public async Task<PagedResult<RoleDto>> Handle(SearchRolesQuery request, CancellationToken cancellationToken)
    {
        // 1. 获取租户上下文并查询角色
        var tenantId = request.TenantId ?? tenantProvider.GetCurrentTenantId();
        var roles = await roleRepository.SearchAsync(tenantId, request.Keyword, cancellationToken);

        // 2. 排序
        var sorted = request.SortBy?.ToLowerInvariant() switch
        {
            "name" => request.SortDescending
                ? roles.OrderByDescending(x => x.Name)
                : roles.OrderBy(x => x.Name),
            _ => request.SortDescending
                ? roles.OrderByDescending(x => x.CreatedAt)
                : roles.OrderBy(x => x.CreatedAt)
        };

        // 3. 分页
        var paged = sorted
            .Skip((request.Page - 1) * request.PageSize)
            .Take(request.PageSize)
            .ToList();

        // 4. 映射 DTO
        var items = paged.Select(role => new RoleDto
        {
            Id = role.Id,
            TenantId = role.TenantId,
            Name = role.Name,
            Code = role.Code,
            Description = role.Description
        }).ToList();

        // 5. 返回分页结果
        return new PagedResult<RoleDto>(items, request.Page, request.PageSize, roles.Count);
    }
}
