/** Jetable. Ce que /team rend vraiment, avant et après la refonte visuelle. */
const BASE = "http://127.0.0.1:4214"

async function signIn(username: string, password: string): Promise<string> {
  const res = await fetch(`${BASE}/api/auth/sign-in/username`, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({ username, password }),
    redirect: "manual",
  })
  const raw = res.headers.getSetCookie()
  if (!raw.length) throw new Error(`no cookie for ${username}: ${res.status} ${await res.text()}`)
  return raw.map((c) => c.split(";")[0]).join("; ")
}

function strip(html: string): string {
  return html
    .replace(/<script[\s\S]*?<\/script>/g, " ")
    .replace(/<style[\s\S]*?<\/style>/g, " ")
    .replace(/<[^>]+>/g, "\n")
    .replace(/&#x27;/g, "'")
    .replace(/&amp;/g, "&")
    .replace(/&middot;|&#183;/g, "·")
    .split("\n")
    .map((s) => s.trim())
    .filter(Boolean)
    .join("\n")
}

async function get(path: string, cookie: string) {
  const res = await fetch(`${BASE}${path}`, { headers: { cookie }, redirect: "manual" })
  const body = res.status === 200 ? await res.text() : ""
  return { status: res.status, location: res.headers.get("location"), body }
}

const who = process.argv[2] ?? "narin"
const pass = process.argv[3] ?? "admin1"
const cookie = await signIn(who, pass)

for (const [label, path] of [
  ["Top management, late", "/team?dept=Top+management"],
  ["Top management, today", "/team?dept=Top+management&tab=today"],
  ["Top management, waiting", "/team?dept=Top+management&tab=waiting"],
  ["Accounting, late", "/team?dept=Accounting"],
] as const) {
  const r = await get(path, cookie)
  console.log(`\n===== ${label} — ${r.status} =====`)
  const text = strip(r.body)
  console.log(text.split("\n").slice(0, 60).join("\n"))
  const selected = (r.body.match(/aria-selected="true"/g) ?? []).length
  console.log(`-- aria-selected=true : ${selected}`)
}

for (const [u, p] of [["malai", "manager1"], ["nattikan", "staff1"]] as const) {
  const c = await signIn(u, p)
  const r = await get("/team", c)
  console.log(`\naccess ${u}: ${r.status} ${r.location ?? ""}`)
}

export {}
