/**
 * Jetable. Interroge le serveur de dev réel, pas le service en direct :
 * ce qui compte est ce que /team renvoie à un vrai navigateur signé.
 */
const BASE = "http://127.0.0.1:4214"

export async function signIn(username: string, password: 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?.() ?? []
  const cookie = raw.map((c) => c.split(";")[0]).join("; ")
  if (!cookie) throw new Error(`pas de cookie pour ${username}: ${res.status} ${await res.text()}`)
  return cookie
}

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

/** Le texte visible, balises retirées, pour compter ce que la page dit vraiment. */
export function visible(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(/\n{2,}/g, "\n")
}

/** Combien de lignes du tableau : chaque <tr> du <tbody>. */
export function bodyRows(html: string): number {
  const body = html.match(/<tbody[\s\S]*?<\/tbody>/g) ?? []
  return body.reduce((n, b) => n + (b.match(/<tr/g) ?? []).length, 0)
}

/** Combien de liens vers une tâche, ids distincts. */
export function taskIds(html: string): string[] {
  const ids = [...html.matchAll(/\/tasks\/([0-9a-f-]{36})/g)].map((m) => m[1]!)
  return [...new Set(ids)]
}
