using MediatR;
using TakeoutSaaS.Application.App.Tenants.Dto;
using TakeoutSaaS.Application.App.Tenants.Queries;
using TakeoutSaaS.Domain.Tenants.Repositories;
using TakeoutSaaS.Shared.Abstractions.Results;

namespace TakeoutSaaS.Application.App.Tenants.Handlers;

/// <summary>
/// 套餐分页查询处理器。
/// </summary>
public sealed class SearchTenantPackagesQueryHandler(ITenantPackageRepository packageRepository)
    : IRequestHandler<SearchTenantPackagesQuery, PagedResult<TenantPackageDto>>
{
    /// <inheritdoc />
    public async Task<PagedResult<TenantPackageDto>> Handle(SearchTenantPackagesQuery request, CancellationToken cancellationToken)
    {
        // 1. 查询套餐
        var packages = await packageRepository.SearchAsync(request.Keyword, request.IsActive, cancellationToken);

        // 2. 排序与分页
        var ordered = packages
            .OrderBy(x => x.SortOrder)
            .ThenByDescending(x => x.CreatedAt)
            .ToList();
        var pageIndex = request.Page <= 0 ? 1 : request.Page;
        var size = request.PageSize <= 0 ? 20 : request.PageSize;
        var pagedItems = ordered
            .Skip((pageIndex - 1) * size)
            .Take(size)
            .Select(x => x.ToDto())
            .ToList();

        // 3. 返回分页结果
        return new PagedResult<TenantPackageDto>(pagedItems, pageIndex, size, ordered.Count);
    }
}
