import { statSync } from "node:fs"

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

/**
 * Open several, close them, and show the server let go.
 *
 *     bun run tmp/sse/cleanup.ts
 *
 * A closed socket only says the client went away. What has to come back to zero
 * is the server's own count of subscribed streams, which the route logs while
 * this is being measured. Reads the delta of the dev server's log.
 */

const LOG = ".next/dev/logs/next-development.log"

async function since(offset: number): Promise<string[]> {
  const text = await Bun.file(LOG).slice(offset).text()
  return text
    .split("\n")
    .filter((l) => l.includes("[sse]"))
    .map((l) => {
      const parsed = JSON.parse(l) as { timestamp: string; message: string }
      return `${parsed.timestamp} ${parsed.message}`
    })
}

const start = statSync(LOG).size

const nattikan = await signIn("nattikan", "staff1")
const narisara = await signIn("narisara", "staff2")

const streams: Stream[] = []
for (let i = 0; i < 8; i++) {
  const stream = new Stream()
  await stream.open(i % 2 === 0 ? nattikan : narisara)
  await stream.waitFor((f) => f.event === "ready")
  streams.push(stream)
}
console.log(`${streams.length} streams open`)
await Bun.sleep(300)

for (const stream of streams) stream.close()
console.log("all closed; waiting for the server to notice")
await Bun.sleep(1_500)

console.log("\nWhat the server logged")
for (const l of await since(start)) console.log("  " + l)

await sql.end()
