import cron from 'node-cron'
import type { HijackAlertsDatabaseClient } from './db-client'
import { WebhookClient } from './webhook-client'

export class RetryScheduler {
  private cronJob: cron.ScheduledTask | null = null
  private isRunning = false

  constructor(private dbClient: HijackAlertsDatabaseClient, private webhookClient: WebhookClient) {}

  start(): void {
    if (this.cronJob) return

    this.cronJob = cron.schedule('*/5 * * * *', async () => {
      if (this.isRunning) return
      this.isRunning = true

      try {
        await this.processFailedDeliveries()
      } catch (error) {
        console.error('[Retry Scheduler] Error processing failed deliveries:', error)
      } finally {
        this.isRunning = false
      }
    })

    console.log('[Retry Scheduler] Started (runs every 5 minutes)')
  }

  stop(): void {
    if (this.cronJob) {
      this.cronJob.stop()
      this.cronJob = null
      console.log('[Retry Scheduler] Stopped')
    }
  }

  private async processFailedDeliveries(): Promise<void> {
    const failedDeliveries = await this.dbClient.getFailedDeliveriesForRetry()

    if (failedDeliveries.length === 0) return

    console.log(`[Retry Scheduler] Processing ${failedDeliveries.length} failed webhook deliveries`)

    for (const { webhook, event, delivery } of failedDeliveries) {
      const result = await this.webhookClient.sendWebhook(event, webhook.endpoint_url, webhook.secret_key, webhook.timeout_ms)

      let newFailureCount = webhook.failure_count
      if (!result.success) {
        newFailureCount += 1
      }

      await this.dbClient.recordWebhookDelivery(webhook.id, event.id, delivery.attempt_number + 1, result.status || null, null, result.error || null)

      if (result.success) {
        await this.dbClient.updateWebhookLastTriggered(webhook.id, 0)
        console.log(`[Retry Scheduler] Webhook ${webhook.id} delivered successfully`)
      } else {
        if (delivery.attempt_number + 1 >= webhook.max_retries) {
          await this.dbClient.updateWebhookStatus(webhook.id, false)
          console.warn(`[Retry Scheduler] Webhook ${webhook.id} disabled after ${webhook.max_retries} failed attempts`)
        } else {
          await this.dbClient.updateWebhookLastTriggered(webhook.id, newFailureCount)
        }
      }
    }
  }
}
