import { logger } from "../util/logger.js";
import { memoize } from "../util/memoize.js";
import { extractCloudflareResult } from "./api-response.js";
import { CloudflareAuth } from "./auth.js";
export const listCloudflareAccounts = memoize(async (credentials) => {
    return await extractCloudflareResult("get accounts for authorized user", fetch("https://api.cloudflare.com/client/v4/accounts", {
        headers: CloudflareAuth.formatHeaders(credentials),
    }));
});
export const getCloudflareAccountId = memoize(async (credentials) => {
    const accounts = await listCloudflareAccounts(credentials);
    if (!accounts[0]) {
        throw new Error("No accounts found for authorized user. Please make sure you're authenticated (see: https://alchemy.run/guides/cloudflare/) or explicitly set the Cloudflare Account ID (see: https://alchemy.run/guides/cloudflare/#account-id)");
    }
    if (accounts.length > 1) {
        logger.warnOnce([
            "Multiple Cloudflare accounts found for authorized user:",
            accounts.map((a, i) => `${i + 1}: ${a.name} (${a.id})`).join("\n"),
            "The first account will be used by default. To use a different account, explicitly set the Cloudflare Account ID (see: https://alchemy.run/guides/cloudflare/#account-id)",
        ].join("\n"));
    }
    return accounts[0].id;
});
export const getUserEmailFromApiKey = memoize(async (apiKey) => {
    const result = await extractCloudflareResult("automatically discover email for API Key authentication", fetch("https://api.cloudflare.com/client/v4/user", {
        headers: {
            "Content-Type": "application/json",
            "X-Auth-Key": apiKey,
        },
    }));
    return result.email;
});
//# sourceMappingURL=user.js.map