const DEFAULT_BASE_URL = "https://api.poe.com";
export async function checkAuth(options) {
    try {
        const fetchImplementation = options.fetch ?? globalThis.fetch;
        const response = await fetchImplementation(createCurrentBalanceUrl(options.baseUrl ?? DEFAULT_BASE_URL), {
            method: "GET",
            headers: {
                Authorization: `Bearer ${options.apiKey}`
            }
        });
        if (!response.ok) {
            return null;
        }
        const data = (await response.json());
        if (!isCurrentBalanceResponse(data)) {
            return null;
        }
        return {
            email: getOwnString(data, "email") ?? null,
            balance: getOwnNumber(data, "current_point_balance") ?? null
        };
    }
    catch {
        return null;
    }
}
function createCurrentBalanceUrl(baseUrl) {
    const url = new URL(baseUrl);
    const path = url.pathname.endsWith("/") ? url.pathname.slice(0, -1) : url.pathname;
    url.pathname = `${path}/usage/current_balance`;
    return url.toString();
}
function isCurrentBalanceResponse(value) {
    if (value === null || typeof value !== "object" || Array.isArray(value)) {
        return false;
    }
    const data = value;
    const email = getOwnString(data, "email");
    const balance = getOwnEntry(data, "current_point_balance");
    const hasEmail = email !== undefined;
    const hasBalance = balance !== undefined;
    if (!hasEmail && !hasBalance) {
        return false;
    }
    return (balance === undefined ||
        balance === null ||
        (typeof balance === "number" && Number.isFinite(balance) && balance >= 0));
}
function getOwnEntry(record, key) {
    return Object.prototype.hasOwnProperty.call(record, key)
        ? record[key]
        : undefined;
}
function getOwnString(record, key) {
    const value = getOwnEntry(record, key);
    if (typeof value !== "string") {
        return undefined;
    }
    const trimmed = value.trim();
    return trimmed.length > 0 ? trimmed : undefined;
}
function getOwnNumber(record, key) {
    const value = getOwnEntry(record, key);
    return typeof value === "number" ? value : undefined;
}
