import { Stream, signIn } from "./harness"
import { sql } from "@/lib/db/client"

/**
 * What an idle connection sends, and when.
 *
 *     bun run tmp/sse/keepalive.ts [seconds]
 */

const seconds = Number(process.argv[2] ?? 50)
const cookie = await signIn("nattikan", "staff1")

const stream = new Stream()
await stream.open(cookie)
await stream.waitFor((f) => f.event === "ready")
console.log(`holding an idle stream for ${seconds} s`)

const started = performance.now()
while (performance.now() - started < seconds * 1_000) await Bun.sleep(100)

const comments = stream.frames.filter((f) => f.comment !== undefined)
console.log("comment frames:", comments.map((f) => ({ at: Math.round(f.at), text: f.comment })))
console.log(
  "gaps (ms):",
  comments.map((f, i) => Math.round(f.at - (i === 0 ? 0 : comments[i - 1]!.at))),
)
console.log("still open:", stream.frames.length > 0)
stream.close()
await sql.end()
