// Jest globalSetup for the integration project.
//
// Runs ONCE before any test file in the integration tier. Responsibilities:
//   1. Detect whether the test rig is configured and print a one-line banner
//      so a developer running `npm run test:integration` for the first time
//      sees "skip mode" vs "live mode" instantly, without reading per-suite
//      skip markers.
//   2. Mint a fresh access token for every Pixelfed slot from its durable
//      refresh token and write it back to the rig — delegated to the shared
//      `scripts/dev/refresh-rig-tokens.mjs` so the mint logic lives in exactly
//      one place (the Maestro wrapper `scripts/dev/run-e2e.sh` runs the same
//      script, since the E2E tier has no globalSetup of its own).
//
// We deliberately do NOT seed the AccountStore here — each test file decides
// which rigs it needs and in what order. globalSetup runs in its own Node
// realm and cannot reach into the mock MMKV that runs inside each test's
// realm anyway. The token mint needs only real network + filesystem, which the
// spawned child has; it writes the rig file on disk and the per-suite loaders
// re-read it fresh in their own realms after globalSetup returns.

import { execFileSync } from 'node:child_process'
import { resolve } from 'node:path'
import { loadTestRig, resolveRigPath, rigHostnames } from '../../_helpers/loadTestRig'

export default async function globalSetup(): Promise<void> {
  const rig = loadTestRig()
  if (!rig) {
    // eslint-disable-next-line no-console
    console.log(
      '[integration] no test rig configured — every suite will skip. ' +
        'Run scripts/dev/bootstrap-test-rig.sh to enable.'
    )
    return
  }
  const slots = Object.keys(rig.rigs)
  const hosts = rigHostnames(rig).length
  // eslint-disable-next-line no-console
  console.log(
    `[integration] rig loaded: ${slots.length} slot(s) [${slots.join(', ')}] across ${hosts} host(s)`
  )

  // __tests__/integration/_setup → repo root is three levels up.
  const script = resolve(
    __dirname,
    '..',
    '..',
    '..',
    'scripts',
    'dev',
    'refresh-rig-tokens.mjs'
  )
  try {
    execFileSync(process.execPath, [script, resolveRigPath()], { stdio: 'inherit' })
  } catch {
    // The script already prints a host-free, actionable warning per slot on a
    // dead refresh token. A non-zero exit here shouldn't abort the whole run —
    // suites with a still-valid stored token (or Mastodon) can still pass.
  }
}
