/**
 * The Thai side of the screen, and the language card doing its job. Throwaway.
 * `bun run tmp/settings/thai.ts`.
 *
 * narin reads English, so this drives the real `setLanguage` action, reads the
 * screen back, and puts the row where it found it. Every one of the three
 * development logins reads English; malai is the Thai reader in the roster and
 * their sign-in was rate-limited by the counter test running before this.
 */

const BASE = "http://127.0.0.1:4214"

async function actionId(path: string, name: string, cookie?: string) {
  const html = await fetch(`${BASE}${path}`, {
    headers: cookie ? { cookie } : {},
  }).then((r) => r.text())
  const chunks = [
    ...new Set(
      [...html.matchAll(/\/_next\/static\/[^"'\\ ]+?\.js/g)].map((m) => m[0]),
    ),
  ]
  const pattern = new RegExp(
    `__next_internal_action_entry_do_not_use__ \\[\\{"([0-9a-f]+)":\\{"name":"${name}"\\}\\}`,
  )
  for (const chunk of chunks) {
    const source = await fetch(`${BASE}${chunk}`).then((r) => r.text())
    const found = source.match(pattern)
    if (found) return found[1]!
  }
  throw new Error(`no action id for ${name}`)
}

const SIGN_IN = await actionId("/login", "attemptSignIn")

const signedIn = await fetch(`${BASE}/login`, {
  method: "POST",
  headers: { "Next-Action": SIGN_IN, "Content-Type": "text/plain;charset=UTF-8" },
  body: JSON.stringify(["narin", "admin1"]),
})
const cookie = signedIn.headers
  .getSetCookie()
  .map((l) => l.split(";")[0]!)
  .join("; ")

const LANGUAGE = await actionId("/settings", "setLanguage", cookie)

async function setLanguage(locale: "en" | "th") {
  const r = await fetch(`${BASE}/settings`, {
    method: "POST",
    headers: {
      "Next-Action": LANGUAGE,
      "Content-Type": "text/plain;charset=UTF-8",
      cookie,
    },
    body: JSON.stringify([locale]),
  })
  return r.status
}

async function screen() {
  const page = await fetch(`${BASE}/settings`, { headers: { cookie } }).then(
    (r) => r.text(),
  )
  return page
    .replace(/<script[\s\S]*?<\/script>/g, " ")
    .replace(/<style[\s\S]*?<\/style>/g, " ")
    .replace(/<[^>]+>/g, "\n")
    .split("\n")
    .map((l) => l.trim())
    .filter(Boolean)
    .slice(-10)
    .join("\n")
}

console.log("set th:", await setLanguage("th"))
console.log(await screen())
console.log("\nset en:", await setLanguage("en"))
console.log(await screen())
