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

namespace TakeoutSaaS.Application.App.Statistics.Handlers;

/// <summary>
/// 获取订阅概览统计处理器。
/// </summary>
public sealed class GetSubscriptionOverviewQueryHandler(IStatisticsRepository statisticsRepository)
    : IRequestHandler<GetSubscriptionOverviewQuery, SubscriptionOverviewDto>
{
    /// <inheritdoc />
    public async Task<SubscriptionOverviewDto> Handle(GetSubscriptionOverviewQuery request, CancellationToken cancellationToken)
    {
        var now = DateTime.UtcNow;
        var in7Days = now.AddDays(7);
        var in3Days = now.AddDays(3);
        var in1Day = now.AddDays(1);

        // 查询所有订阅
        var subscriptions = await statisticsRepository.GetAllSubscriptionsAsync(cancellationToken);

        // 统计各项数据
        var overview = new SubscriptionOverviewDto
        {
            TotalActive = subscriptions.Count(s => s.Status == SubscriptionStatus.Active),
            ExpiringIn7Days = subscriptions.Count(s =>
                s.Status == SubscriptionStatus.Active &&
                s.EffectiveTo >= now &&
                s.EffectiveTo <= in7Days),
            ExpiringIn3Days = subscriptions.Count(s =>
                s.Status == SubscriptionStatus.Active &&
                s.EffectiveTo >= now &&
                s.EffectiveTo <= in3Days),
            ExpiringIn1Day = subscriptions.Count(s =>
                s.Status == SubscriptionStatus.Active &&
                s.EffectiveTo >= now &&
                s.EffectiveTo <= in1Day),
            Expired = subscriptions.Count(s => s.Status == SubscriptionStatus.GracePeriod),
            Pending = subscriptions.Count(s => s.Status == SubscriptionStatus.Pending),
            Suspended = subscriptions.Count(s => s.Status == SubscriptionStatus.Suspended)
        };

        return overview;
    }
}
