/**
 * Runs once before all tests. Waits for the test stack to be healthy, logs
 * in as admin, and flips all rate-limit/quota toggles off so tests don't
 * trip over them. Individual tests that *want* to assert rate-limit
 * behaviour re-enable the relevant flags in `beforeAll` and restore them
 * in `afterAll`.
 *
 * The admin token is written to `.cache/admin-token` so per-worker
 * fixtures can read it instead of logging in repeatedly.
 */
import { ApiClient } from './fixtures/api-client';
import { mkdir, writeFile } from 'node:fs/promises';
import { join } from 'node:path';

const CACHE_DIR = join(process.cwd(), '.cache');

export default async function globalSetup() {
  const api = new ApiClient();

  console.log('[e2e] waiting for backend health…');
  await api.waitForHealth(120);

  console.log('[e2e] logging in admin…');
  const adminToken = await api.adminLogin();

  console.log('[e2e] resetting database…');
  await api.truncate(adminToken);

  // Re-login because truncate wiped the session row backing the previous token.
  const freshAdminToken = await api.adminLogin();

  console.log('[e2e] disabling rate limits & quotas for the test run…');
  await api.patchConfig(freshAdminToken, {
    rate_limits_enabled: 'false',
    upload_rate_enabled: 'false',
    feed_rate_enabled: 'false',
    export_rate_enabled: 'false',
    join_rate_enabled: 'false',
    quota_enabled: 'false',
    storage_quota_enabled: 'false',
    upload_count_quota_enabled: 'false',
  });

  await mkdir(CACHE_DIR, { recursive: true });
  await writeFile(join(CACHE_DIR, 'admin-token'), freshAdminToken, 'utf8');
  console.log('[e2e] global setup complete');
}
