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 SearchPermissionsQueryHandler(
    IPermissionRepository permissionRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<SearchPermissionsQuery, PagedResult<PermissionDto>>
{
    /// <summary>
    /// 执行权限分页查询。
    /// </summary>
    /// <param name="request">查询参数。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>分页结果。</returns>
    public async Task<PagedResult<PermissionDto>> Handle(SearchPermissionsQuery request, CancellationToken cancellationToken)
    {
        // 1. 获取租户上下文并查询权限
        var tenantId = tenantProvider.GetCurrentTenantId();
        var permissions = await permissionRepository.SearchAsync(tenantId, request.Keyword, cancellationToken);

        // 2. 排序
        var sorted = request.SortBy?.ToLowerInvariant() switch
        {
            "name" => request.SortDescending
                ? permissions.OrderByDescending(x => x.Name)
                : permissions.OrderBy(x => x.Name),
            "code" => request.SortDescending
                ? permissions.OrderByDescending(x => x.Code)
                : permissions.OrderBy(x => x.Code),
            "parentid" => request.SortDescending
                ? permissions.OrderByDescending(x => x.ParentId).ThenByDescending(x => x.SortOrder)
                : permissions.OrderBy(x => x.ParentId).ThenBy(x => x.SortOrder),
            "type" => request.SortDescending
                ? permissions.OrderByDescending(x => x.Type).ThenByDescending(x => x.SortOrder)
                : permissions.OrderBy(x => x.Type).ThenBy(x => x.SortOrder),
            "sortorder" => request.SortDescending
                ? permissions.OrderByDescending(x => x.SortOrder).ThenByDescending(x => x.CreatedAt)
                : permissions.OrderBy(x => x.SortOrder).ThenBy(x => x.CreatedAt),
            _ => request.SortDescending
                ? permissions.OrderByDescending(x => x.SortOrder).ThenByDescending(x => x.CreatedAt)
                : permissions.OrderBy(x => x.SortOrder).ThenBy(x => x.CreatedAt)
        };

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

        // 4. 映射 DTO
        var items = paged.Select(permission => new PermissionDto
        {
            Id = permission.Id,
            TenantId = permission.TenantId,
            ParentId = permission.ParentId,
            SortOrder = permission.SortOrder,
            Type = permission.Type,
            Name = permission.Name,
            Code = permission.Code,
            Description = permission.Description
        }).ToList();

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