"use strict";
/**
 * Shared helpers for the end-to-end process runner.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.setBase = setBase;
exports.getBase = getBase;
exports.log = log;
exports.header = header;
exports.api = api;
exports.login = login;
exports.sleep = sleep;
exports.poll = poll;
let _base = 'http://localhost:3000';
function setBase(url) {
    _base = url;
}
function getBase() {
    return _base;
}
function log(role, msg) {
    const label = role.padEnd(10);
    console.log(`  ${label} │ ${msg}`);
}
function header(text) {
    console.log(`\n  ─── ${text} ${'─'.repeat(Math.max(0, 58 - text.length))}\n`);
}
async function api(method, path, token, body) {
    const res = await fetch(`${_base}/api${path}`, {
        method,
        headers: {
            'Content-Type': 'application/json',
            ...(token ? { Authorization: `Bearer ${token}` } : {}),
        },
        body: body ? JSON.stringify(body) : undefined,
    });
    const json = await res.json();
    if (!res.ok) {
        throw new Error(`${method} ${path} → ${res.status}: ${JSON.stringify(json)}`);
    }
    return json;
}
async function login(username, password) {
    const { token } = await api('POST', '/auth/login', '', { username, password });
    return token;
}
async function sleep(ms) {
    return new Promise((r) => setTimeout(r, ms));
}
async function poll(label, fn, timeoutMs = 30_000, intervalMs = 1_000) {
    const start = Date.now();
    while (Date.now() - start < timeoutMs) {
        const result = await fn();
        if (result)
            return result;
        await sleep(intervalMs);
    }
    throw new Error(`Timed out waiting for: ${label}`);
}
