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

namespace TakeoutSaaS.Application.App.Subscriptions.Handlers;

/// <summary>
/// 订阅分页查询处理器。
/// </summary>
public sealed class GetSubscriptionListQueryHandler(
    ISubscriptionRepository subscriptionRepository)
    : IRequestHandler<GetSubscriptionListQuery, PagedResult<SubscriptionListDto>>
{
    /// <inheritdoc />
    public async Task<PagedResult<SubscriptionListDto>> Handle(GetSubscriptionListQuery request, CancellationToken cancellationToken)
    {
        // 1. 构建查询过滤条件
        var filter = new SubscriptionSearchFilter
        {
            Status = request.Status,
            TenantPackageId = request.TenantPackageId,
            TenantId = request.TenantId,
            TenantKeyword = request.TenantKeyword,
            ExpiringWithinDays = request.ExpiringWithinDays,
            AutoRenew = request.AutoRenew,
            Page = request.Page,
            PageSize = request.PageSize
        };

        // 2. 执行分页查询
        var (items, total) = await subscriptionRepository.SearchPagedAsync(
            filter,
            cancellationToken);

        // 3. 映射为 DTO
        var dtos = items.Select(x => new SubscriptionListDto
        {
            Id = x.Subscription.Id,
            TenantId = x.Subscription.TenantId,
            TenantName = x.TenantName,
            TenantCode = x.TenantCode,
            TenantPackageId = x.Subscription.TenantPackageId,
            PackageName = x.PackageName,
            ScheduledPackageId = x.Subscription.ScheduledPackageId,
            ScheduledPackageName = x.ScheduledPackageName,
            Status = x.Subscription.Status,
            EffectiveFrom = x.Subscription.EffectiveFrom,
            EffectiveTo = x.Subscription.EffectiveTo,
            NextBillingDate = x.Subscription.NextBillingDate,
            AutoRenew = x.Subscription.AutoRenew,
            Notes = x.Subscription.Notes,
            CreatedAt = x.Subscription.CreatedAt,
            UpdatedAt = x.Subscription.UpdatedAt
        }).ToList();

        // 4. 返回分页结果
        return new PagedResult<SubscriptionListDto>(dtos, request.Page, request.PageSize, total);
    }
}
