using MediatR;
using TakeoutSaaS.Application.App.Subscriptions.Contracts;
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 ListSubscriptionsQueryHandler(ISubscriptionRepository subscriptionRepository)
    : IRequestHandler<ListSubscriptionsQuery, PagedResult<SubscriptionListDto>>
{
    /// <inheritdoc />
    public async Task<PagedResult<SubscriptionListDto>> Handle(
        ListSubscriptionsQuery request,
        CancellationToken cancellationToken)
    {
        // 1. 查询订阅列表
        var (items, totalCount) = await subscriptionRepository.GetListAsync(
            request.Status,
            request.TenantPackageId,
            request.TenantId,
            request.TenantKeyword,
            request.ExpiringWithinDays,
            request.AutoRenew,
            request.ExpireFrom,
            request.ExpireTo,
            request.Page,
            request.PageSize,
            cancellationToken);

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

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