using Books.Api.Banking;
using Hangfire;

namespace Books.Api.Ledger;

public static class LedgerJobsExtensions
{
    /// <summary>
    /// Configures Ledger-related Hangfire jobs.
    /// Should be called after Hangfire is fully initialized.
    /// </summary>
    public static void ConfigureLedgerJobs(this IApplicationBuilder app)
    {
        // Use DI-based IRecurringJobManager instead of static RecurringJob
        // This works correctly in test environments where JobStorage may not be initialized
        var recurringJobManager = app.ApplicationServices.GetService<IRecurringJobManager>();
        if (recurringJobManager == null)
        {
            // In test environment, Hangfire may not be fully configured
            return;
        }

        // Poll Ledger outbox every 5 seconds for new transaction events
        recurringJobManager.AddOrUpdate<LedgerOutboxConsumer>(
            "ledger-outbox-consumer",
            x => x.ProcessPendingEventsAsync(),
            "*/5 * * * * *"); // Every 5 seconds (cron with seconds)

        // Sync bank transactions from Enable Banking every 30 minutes
        recurringJobManager.AddOrUpdate<BankTransactionSyncJob>(
            "bank-transaction-sync",
            x => x.SyncAllActiveConnectionsAsync(default),
            "*/30 * * * *"); // Every 30 minutes

        // Reconcile bank accounts with ledger accounts daily at 6:00 AM
        recurringJobManager.AddOrUpdate<BankReconciliationJob>(
            "bank-reconciliation",
            x => x.ReconcileAllAsync(default),
            "0 6 * * *"); // Daily at 06:00
    }
}
