using MediatR;
using TakeoutSaaS.Application.App.Statistics.Dto;
using TakeoutSaaS.Application.App.Statistics.Queries;
using TakeoutSaaS.Domain.Tenants.Repositories;

namespace TakeoutSaaS.Application.App.Statistics.Handlers;

/// <summary>
/// 获取即将到期的订阅列表处理器。
/// </summary>
public sealed class GetExpiringSubscriptionsQueryHandler(IStatisticsRepository statisticsRepository)
    : IRequestHandler<GetExpiringSubscriptionsQuery, IReadOnlyList<ExpiringSubscriptionDto>>
{
    /// <inheritdoc />
    public async Task<IReadOnlyList<ExpiringSubscriptionDto>> Handle(GetExpiringSubscriptionsQuery request, CancellationToken cancellationToken)
    {
        var now = DateTime.UtcNow;

        // 查询即将到期的订阅
        var items = await statisticsRepository.GetExpiringSubscriptionsAsync(
            request.DaysAhead,
            request.OnlyWithoutAutoRenew,
            cancellationToken);

        // 映射为 DTO
        return items.Select(x => new ExpiringSubscriptionDto
        {
            Id = x.Subscription.Id,
            TenantId = x.Subscription.TenantId.ToString(),
            TenantName = x.TenantName,
            PackageName = x.PackageName,
            Status = x.Subscription.Status,
            EffectiveTo = x.Subscription.EffectiveTo,
            DaysRemaining = (int)(x.Subscription.EffectiveTo - now).TotalDays,
            AutoRenew = x.Subscription.AutoRenew
        }).ToList();
    }
}
