/**
 * SAC HTTP client
 */
import { SACError, ExitCode, mapApiError } from "./errors.js";
export async function request(config, opts, apiKey) {
    const headers = {
        "Content-Type": "application/json",
        "User-Agent": "seawork-sac/1.0.0",
        ...opts.headers,
    };
    if (!opts.noAuth) {
        const token = apiKey || config.apiKey;
        if (!token) {
            throw new SACError("No API key found.", ExitCode.AUTH, "Set env var:    export SAC_API_KEY=<token>\nOr add to:      ~/.seawork/auth.json");
        }
        headers["Authorization"] = `Bearer ${token}`;
        if (config.verbose) {
            process.stderr.write(`> ${opts.method ?? "GET"} ${opts.url}\n`);
            process.stderr.write(`> Auth: ${token.slice(0, 8)}...\n`);
        }
    }
    const timeoutMs = (opts.timeout ?? config.timeout) * 1000;
    let res;
    try {
        res = await fetch(opts.url, {
            method: opts.method ?? "GET",
            headers,
            body: opts.body ? JSON.stringify(opts.body) : undefined,
            signal: AbortSignal.timeout(timeoutMs),
        });
    }
    catch (err) {
        if (err instanceof Error) {
            if (err.name === "TimeoutError" || err.name === "AbortError") {
                throw new SACError(`Request timed out after ${config.timeout}s`, ExitCode.TIMEOUT, "Try increasing --timeout or retry later.");
            }
            if (err.message.includes("ECONNREFUSED") ||
                err.message.includes("ENOTFOUND") ||
                err.message.includes("fetch failed")) {
                throw new SACError(`Network error: ${err.message}`, ExitCode.NETWORK, "Check your network connection.");
            }
        }
        throw err;
    }
    if (config.verbose) {
        process.stderr.write(`< ${res.status} ${res.statusText}\n`);
    }
    if (!res.ok) {
        let body = {};
        try {
            body = (await res.json());
        }
        catch {
            /* non-JSON */
        }
        throw mapApiError(res.status, body, opts.url);
    }
    return res;
}
export async function requestJson(config, opts, apiKey) {
    const res = await request(config, opts, apiKey);
    try {
        return (await res.json());
    }
    catch {
        const contentType = res.headers.get("content-type") || "";
        throw new SACError(`API returned non-JSON response (${contentType || "unknown type"}). Server may be experiencing issues.`, ExitCode.GENERAL);
    }
}
//# sourceMappingURL=client.js.map