import cron from "node-cron"
import * as Sentry from "@sentry/node"
import { App } from "octokit"
import { syncOrgsWithMembers } from "../github/github-utils.js"
import { sendStatusEmail } from "../resend/email-service.js"
import { CRON_DAILY_MIDNIGHT } from "../constants/index.js"

let isRunning = false

/**
 * Initialize all cron jobs
 */
export function initializeCronJobs(githubApp: App): void {
  // Sync organizations with members - runs daily at midnight UTC
  cron.schedule(CRON_DAILY_MIDNIGHT, async () => {
    if (isRunning) return
    isRunning = true
    const startTime = new Date()

    try {
      await syncOrgsWithMembers(githubApp)
      console.log("Finished syncOrgsWithMembers cron job.")
    } catch (error: any) {
      console.error("Error running syncOrgsWithMembers cron job:", error)
      Sentry.captureException(error)
      const endTime = new Date()
      const duration = endTime.getTime() - startTime.getTime()
      const durationHms = `${Math.floor(duration / 3600000)}h ${Math.floor((duration % 3600000) / 60000)}m ${Math.floor((duration % 60000) / 1000)}s`
      const errorDetails = error.stack || error.message || String(error)
      await sendStatusEmail("Failed", startTime, endTime, durationHms, errorDetails)
    } finally {
      isRunning = false
    }
  })

  console.log("Cron jobs initialized")
}
