import assert from "node:assert/strict"
import {
  SQLITE_BUSY_TIMEOUT_MS,
  SQLITE_CACHE_SIZE_KIB,
  SQLITE_WAL_AUTOCHECKPOINT_PAGES,
  sqliteDatabase,
} from "../db/index.js"
import {
  MAX_FLOW_LIVE_SUBSCRIBERS,
  resetFlowLiveSlotsForTests,
  tryAcquireFlowLiveSlot,
  releaseFlowLiveSlot,
} from "../routes/traffic-flow.js"

const busy = sqliteDatabase.pragma("busy_timeout") as Array<{ busy_timeout: number }>
const busyValue = Array.isArray(busy) ? Number(Object.values(busy[0] ?? {})[0]) : Number(busy)
assert.equal(busyValue, SQLITE_BUSY_TIMEOUT_MS)

function pragmaNum(name: string): number {
  const rows = sqliteDatabase.pragma(name) as Array<Record<string, number>>
  const row = Array.isArray(rows) ? rows[0] : rows
  return Number(Object.values(row ?? {})[0])
}

assert.equal(pragmaNum("wal_autocheckpoint"), SQLITE_WAL_AUTOCHECKPOINT_PAGES)
assert.equal(pragmaNum("cache_size"), -SQLITE_CACHE_SIZE_KIB)
assert.equal(pragmaNum("temp_store"), 2)

resetFlowLiveSlotsForTests()
for (let i = 0; i < MAX_FLOW_LIVE_SUBSCRIBERS; i++) {
  assert.equal(tryAcquireFlowLiveSlot(), true)
}
assert.equal(tryAcquireFlowLiveSlot(), false)
releaseFlowLiveSlot()
assert.equal(tryAcquireFlowLiveSlot(), true)
resetFlowLiveSlotsForTests()

console.log("traffic-flow-hardening.test.ts: ok")
