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 SubscriptionAutoRenewalJob(
    IMediator mediator,
    IOptionsMonitor<SubscriptionAutomationOptions> optionsMonitor,
    ILogger<SubscriptionAutoRenewalJob> logger)
{
    /// <summary>
    /// 执行自动续费账单生成。
    /// </summary>
    public async Task ExecuteAsync()
    {
        // 1. 读取配置并执行自动续费
        var options = optionsMonitor.CurrentValue;
        var result = await mediator.Send(new ProcessAutoRenewalCommand
        {
            RenewalDaysBeforeExpiry = options.AutoRenewalDaysBeforeExpiry
        });

        // 2. 记录执行结果
        logger.LogInformation(
            "定时任务：自动续费处理完成，候选 {CandidateCount}，创建账单 {CreatedBillCount}",
            result.CandidateCount,
            result.CreatedBillCount);
    }
}

