using MediatR;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using TakeoutSaaS.Application.App.Subscriptions.Commands;
using TakeoutSaaS.Module.Scheduler.Options;

namespace TakeoutSaaS.Module.Scheduler.Jobs;

/// <summary>
/// 订阅到期检查任务：到期进入宽限期，宽限期到期自动暂停。
/// </summary>
public sealed class SubscriptionExpiryCheckJob(
    IMediator mediator,
    IOptionsMonitor<SubscriptionAutomationOptions> optionsMonitor,
    ILogger<SubscriptionExpiryCheckJob> logger)
{
    /// <summary>
    /// 执行订阅到期检查。
    /// </summary>
    public async Task ExecuteAsync()
    {
        // 1. 读取配置并执行到期处理
        var options = optionsMonitor.CurrentValue;
        var result = await mediator.Send(new ProcessSubscriptionExpiryCommand
        {
            GracePeriodDays = options.GracePeriodDays
        });

        // 2. 记录执行结果
        logger.LogInformation(
            "定时任务：订阅到期检查完成，进入宽限期 {EnteredGracePeriodCount}，暂停 {SuspendedCount}",
            result.EnteredGracePeriodCount,
            result.SuspendedCount);
    }
}
