using Hangfire;
using Microsoft.Extensions.Options;
using TakeoutSaaS.Module.Scheduler.Abstractions;
using TakeoutSaaS.Module.Scheduler.Jobs;
using TakeoutSaaS.Module.Scheduler.Options;

namespace TakeoutSaaS.Module.Scheduler.Services;

/// <summary>
/// 周期性任务注册器。
/// </summary>
public sealed class RecurringJobRegistrar(
    IOptionsMonitor<SubscriptionAutomationOptions> subscriptionAutomationOptions,
    IOptionsMonitor<BillingAutomationOptions> billingAutomationOptions)
    : IRecurringJobRegistrar
{
    /// <inheritdoc />
    public Task RegisterAsync(CancellationToken cancellationToken = default)
    {
        // 1. 业务占位任务（示例）
        RecurringJob.AddOrUpdate<OrderTimeoutJob>("orders.timeout-cancel", job => job.ExecuteAsync(), "*/5 * * * *");
        RecurringJob.AddOrUpdate<OrderEscalationJob>("orders.escalation-sms", job => job.ExecuteAsync(), "*/2 * * * *");
        RecurringJob.AddOrUpdate<CouponExpireJob>("coupons.expire", job => job.ExecuteAsync(), "0 */1 * * *");
        RecurringJob.AddOrUpdate<LogCleanupJob>("logs.cleanup", job => job.ExecuteAsync(), "0 3 * * *");

        // 2. 订阅自动化任务（自动续费、续费提醒、到期进入宽限期）
        var options = subscriptionAutomationOptions.CurrentValue;
        RecurringJob.AddOrUpdate<SubscriptionAutoRenewalJob>(
            "subscriptions.auto-renewal",
            job => job.ExecuteAsync(),
            $"0 {options.AutoRenewalExecuteHourUtc} * * *");
        RecurringJob.AddOrUpdate<SubscriptionRenewalReminderJob>(
            "subscriptions.renewal-reminder",
            job => job.ExecuteAsync(),
            $"0 {options.RenewalReminderExecuteHourUtc} * * *");
        RecurringJob.AddOrUpdate<SubscriptionExpiryCheckJob>(
            "subscriptions.expiry-check",
            job => job.ExecuteAsync(),
            $"0 {options.SubscriptionExpiryCheckExecuteHourUtc} * * *");

        // 3. 账单自动化任务（逾期标记）
        var billingOptions = billingAutomationOptions.CurrentValue;
        RecurringJob.AddOrUpdate<BillingOverdueProcessJob>(
            "billings.overdue-process",
            job => job.ExecuteAsync(),
            billingOptions.OverdueBillingProcessCron);

        // 4. 经营报表快照刷新任务
        RecurringJob.AddOrUpdate<FinanceBusinessReportRefreshJob>(
            "finance.business-report-refresh",
            job => job.ExecuteAsync(),
            "*/10 * * * *");

        // 5. (空行后) 门店管理自动化任务
        RecurringJob.AddOrUpdate<BusinessStatusAutoSwitchJob>(
            "stores.business-status-auto-switch",
            job => job.ExecuteAsync(),
            "*/1 * * * *");
        RecurringJob.AddOrUpdate<QualificationExpiryCheckJob>(
            "stores.qualification-expiry-check",
            job => job.ExecuteAsync(),
            "0 2 * * *");

        return Task.CompletedTask;
    }
}
