import { DEFAULT_CREDENTIALS } from "./auth.js";
const BASE_URL = process.env.BASE_URL?.trim() || null;
function resolveUrl(path) {
  return BASE_URL ? `${BASE_URL}${path}` : path;
}
const tokenCache = /* @__PURE__ */ new Map();
const TOKEN_TTL_MS = 45 * 60 * 1e3;
async function getAuthToken(request, roleOrEmail = "admin", password) {
  const role = roleOrEmail in DEFAULT_CREDENTIALS ? roleOrEmail : null;
  const credentialAttempts = [];
  if (role) {
    const configured = DEFAULT_CREDENTIALS[role];
    credentialAttempts.push({ email: configured.email, password: password ?? configured.password });
    if (!password) {
      credentialAttempts.push({ email: `${role}@acme.com`, password: "secret" });
    }
  } else {
    credentialAttempts.push({ email: roleOrEmail, password: password ?? "secret" });
  }
  const cacheKey = credentialAttempts.map((entry) => `${entry.email}:${entry.password}`).join("|");
  const cached = tokenCache.get(cacheKey);
  if (cached && Date.now() - cached.mintedAt < TOKEN_TTL_MS) {
    return cached.token;
  }
  let lastStatus = 0;
  for (const attempt of credentialAttempts) {
    const form = new URLSearchParams();
    form.set("email", attempt.email);
    form.set("password", attempt.password);
    for (let retry = 0; retry < 4; retry += 1) {
      const response = await request.post(resolveUrl("/api/auth/login"), {
        headers: {
          "content-type": "application/x-www-form-urlencoded"
        },
        data: form.toString()
      });
      const raw = await response.text();
      let body = null;
      try {
        body = raw ? JSON.parse(raw) : null;
      } catch {
        body = null;
      }
      lastStatus = response.status();
      if (response.ok() && body && typeof body.token === "string" && body.token) {
        tokenCache.set(cacheKey, { token: body.token, mintedAt: Date.now() });
        return body.token;
      }
      if (response.status() !== 429) break;
      const backoffMs = 1e3 * 2 ** retry;
      await new Promise((resolve) => setTimeout(resolve, backoffMs));
    }
  }
  throw new Error(`Failed to obtain auth token (status ${lastStatus})`);
}
async function apiRequest(request, method, path, options) {
  const headers = {
    Authorization: `Bearer ${options.token}`,
    "Content-Type": "application/json"
  };
  const timeout = options.timeout ?? 3e4;
  let lastError = null;
  for (let attempt = 0; attempt < 2; attempt += 1) {
    try {
      return await request.fetch(resolveUrl(path), { method, headers, data: options.data, timeout });
    } catch (error) {
      lastError = error;
      const message = error instanceof Error ? error.message : "";
      const retryable = /timeout|idle-session|socket|ECONNRESET|Target page, context or browser has been closed/i.test(message);
      if (!retryable || attempt === 1) throw error;
      await new Promise((resolve) => setTimeout(resolve, 250));
    }
  }
  throw lastError;
}
async function postForm(request, path, data, options) {
  const form = new URLSearchParams();
  for (const [key, value] of Object.entries(data)) form.set(key, value);
  return request.post(resolveUrl(path), {
    headers: {
      "content-type": "application/x-www-form-urlencoded",
      ...options?.headers ?? {}
    },
    data: form.toString()
  });
}
export {
  apiRequest,
  getAuthToken,
  postForm
};
//# sourceMappingURL=api.js.map
