import { desc, eq } from "drizzle-orm"
import { db } from "../../../db/index.js"
import { serverSnapshots, servers } from "../../../db/schema.js"

export type ServerRow = typeof servers.$inferSelect
export type SnapshotRow = typeof serverSnapshots.$inferSelect

export function listServerRows(): ServerRow[] {
  return db.select().from(servers).all()
}

export function getServerRowById(id: number): ServerRow | undefined {
  return db.select().from(servers).where(eq(servers.id, id)).limit(1).all()[0]
}

export function createServerRow(
  values: Omit<typeof servers.$inferInsert, "id">,
): ServerRow {
  const [inserted] = db.insert(servers).values(values).returning().all()
  return inserted
}

export function updateServerRowById(
  id: number,
  values: Partial<ServerRow>,
): ServerRow {
  const [updated] = db.update(servers).set(values).where(eq(servers.id, id)).returning().all()
  return updated
}

export function deleteServerRowById(id: number): void {
  db.delete(servers).where(eq(servers.id, id)).run()
}

export function listSnapshotsByServerId(serverId: number, limit: number): SnapshotRow[] {
  return db
    .select()
    .from(serverSnapshots)
    .where(eq(serverSnapshots.serverId, serverId))
    .orderBy(desc(serverSnapshots.polledAt))
    .limit(limit)
    .all()
}

export function getLatestSnapshot(serverId: number): SnapshotRow | undefined {
  return db
    .select()
    .from(serverSnapshots)
    .where(eq(serverSnapshots.serverId, serverId))
    .orderBy(desc(serverSnapshots.polledAt))
    .limit(1)
    .all()[0]
}
