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 GetPublicTenantPackagesQueryHandler(ITenantPackageRepository packageRepository)
    : IRequestHandler<GetPublicTenantPackagesQuery, PagedResult<TenantPackageDto>>
{
    /// <inheritdoc />
    public async Task<PagedResult<TenantPackageDto>> Handle(GetPublicTenantPackagesQuery request, CancellationToken cancellationToken)
    {
        // 1. 仅查询启用套餐
        var packages = await packageRepository.SearchAsync(null, true, cancellationToken);
        // 2. 规范化分页参数
        var pageIndex = request.Page <= 0 ? 1 : request.Page;
        var size = request.PageSize <= 0 ? 20 : request.PageSize;
        // 3. 执行排序、分页与映射
        var ordered = packages
            .OrderBy(x => x.SortOrder)
            .ThenByDescending(x => x.CreatedAt)
            .ToList();
        var items = ordered
            .Skip((pageIndex - 1) * size)
            .Take(size)
            .Select(x => x.ToDto())
            .ToList();
        // 4. 返回分页结果
        return new PagedResult<TenantPackageDto>(items, pageIndex, size, ordered.Count);
    }
}
