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

namespace TakeoutSaaS.Application.App.TenantPackages.Handlers;

/// <summary>
/// 获取租户套餐列表查询处理器。
/// </summary>
public sealed class ListTenantPackagesQueryHandler(ITenantPackageRepository tenantPackageRepository)
    : IRequestHandler<ListTenantPackagesQuery, PagedResult<TenantPackageListDto>>
{
    /// <inheritdoc />
    public async Task<PagedResult<TenantPackageListDto>> Handle(
        ListTenantPackagesQuery request,
        CancellationToken cancellationToken)
    {
        // 1. 查询租户套餐（分页）
        var (packages, totalCount) = await tenantPackageRepository.GetListAsync(
            request.Keyword,
            request.IsActive,
            request.Page,
            request.PageSize,
            cancellationToken);

        // 2. 映射为 DTO
        var items = packages.Select(p => new TenantPackageListDto
        {
            Id = p.Id,
            Name = p.Name,
            Description = p.Description,
            PackageType = p.PackageType,
            MonthlyPrice = p.MonthlyPrice,
            YearlyPrice = p.YearlyPrice,
            MaxStoreCount = p.MaxStoreCount,
            MaxAccountCount = p.MaxAccountCount,
            MaxStorageGb = p.MaxStorageGb,
            MaxSmsCredits = p.MaxSmsCredits,
            MaxDeliveryOrders = p.MaxDeliveryOrders,
            FeaturePoliciesJson = p.FeaturePoliciesJson,
            IsActive = p.IsActive,
            IsPublicVisible = p.IsPublicVisible,
            IsAllowNewTenantPurchase = p.IsAllowNewTenantPurchase,
            PublishStatus = p.PublishStatus,
            IsRecommended = p.IsRecommended,
            Tags = p.Tags,
            SortOrder = p.SortOrder
        }).ToList();

        // 3. 返回分页结果
        return new PagedResult<TenantPackageListDto>(items, totalCount, request.Page, request.PageSize);
    }
}
