using MediatR;
using TakeoutSaaS.Application.Identity.Contracts;
using TakeoutSaaS.Application.Identity.Queries;
using TakeoutSaaS.Domain.Identity.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;
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 currentTenantId = tenantProvider.GetCurrentTenantId();
        if (currentTenantId <= 0)
        {
            throw new BusinessException(ErrorCodes.BadRequest, "缺少租户标识");
        }

        // 2. (空行后) 禁止跨租户查询
        if (request.TenantId.HasValue && request.TenantId.Value != currentTenantId)
        {
            throw new BusinessException(ErrorCodes.Forbidden, "禁止跨租户查询角色");
        }

        // 3. (空行后) 查询角色列表
        var tenantId = currentTenantId;
        var roles = await roleRepository.SearchAsync(tenantId, request.Keyword, cancellationToken);

        // 4. (空行后) 排序
        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)
        };

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

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

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