import { desc, eq, inArray } from "drizzle-orm"
import { db } from "../../db/index.js"
import { alertEngineCursor, schedulerRuns } from "../../db/schema.js"

const SOURCE_JOBS = [
  "traffic",
  "servers_rest_ping",
  "uptime_resources",
  "uptime_ping",
  "uptime_speed",
  "gre_bgp",
] as const

export function getLatestSourceFinishedAt(): string | null {
  const row = db
    .select({ finishedAt: schedulerRuns.finishedAt })
    .from(schedulerRuns)
    .where(inArray(schedulerRuns.jobKey, [...SOURCE_JOBS]))
    .orderBy(desc(schedulerRuns.finishedAt))
    .limit(1)
    .all()[0]
  return row?.finishedAt ?? null
}

export function getSourceWatermark(): string | null {
  const row = db.select().from(alertEngineCursor).where(eq(alertEngineCursor.id, 1)).limit(1).all()[0]
  return row?.lastSourceFinishedAt ?? null
}

export function updateSourceWatermark(lastSourceFinishedAt: string | null): void {
  const existing = db
    .select()
    .from(alertEngineCursor)
    .where(eq(alertEngineCursor.id, 1))
    .limit(1)
    .all()[0]
  if (existing) {
    db.update(alertEngineCursor)
      .set({
        lastSourceFinishedAt,
        updatedAt: new Date().toISOString(),
      })
      .where(eq(alertEngineCursor.id, 1))
      .run()
    return
  }
  db.insert(alertEngineCursor)
    .values({
      id: 1,
      lastSourceFinishedAt,
      updatedAt: new Date().toISOString(),
    })
    .run()
}
