import {
  z
} from "./chunk-5TQBOAE7.js";
import {
  FRAGMENT_ACCESS_TOKEN_PATH
} from "./chunk-WS2PJBP6.js";
import {
  init_cjs_shims
} from "./chunk-7GH3YGSC.js";

// src/lib/auth.ts
init_cjs_shims();
import { existsSync, readFileSync, writeFileSync } from "fs";
var DEFAULT_TOKEN_EXPIRATION_MS = 3600 * 1e3;
var AccessTokenSchema = z.object({
  access_token: z.string(),
  expires_in: z.number(),
  // 3600
  token_type: z.literal("Bearer"),
  created_ms: z.number().optional().default(() => Date.now() - DEFAULT_TOKEN_EXPIRATION_MS)
});
var btoa = (str) => Buffer.from(str).toString("base64");
var getToken = async (authConfig) => {
  const { clientId, clientSecret, oauthUrl, oauthScope } = authConfig;
  const body = new URLSearchParams();
  body.append("grant_type", "client_credentials");
  body.append("client_id", clientId);
  body.append("scope", oauthScope);
  const auth = btoa(`${clientId}:${clientSecret}`);
  const headers = {
    "Content-Type": "application/x-www-form-urlencoded",
    Authorization: `Basic ${auth}`,
    Accept: "*/*"
  };
  const res = await fetch(oauthUrl, {
    method: "POST",
    body,
    headers
  });
  const token = await res.json();
  if (!token.access_token) {
    throw new Error("Didn't get an access token from auth endpoint");
  }
  return {
    ...token,
    created_ms: Date.now()
  };
};
var attemptToCacheToken = (debug, token) => {
  try {
    debug(`Writing to ${FRAGMENT_ACCESS_TOKEN_PATH}`);
    writeFileSync(FRAGMENT_ACCESS_TOKEN_PATH, JSON.stringify(token, null, 2));
  } catch (e) {
    debug(`Failed to write token: ${e}`);
  }
};
var readUnexpiredAccessToken = (debug) => {
  try {
    if (existsSync(FRAGMENT_ACCESS_TOKEN_PATH)) {
      debug(`Reading token from ${FRAGMENT_ACCESS_TOKEN_PATH}`);
      const parsedResult = AccessTokenSchema.safeParse(
        JSON.parse(readFileSync(FRAGMENT_ACCESS_TOKEN_PATH, "utf8"))
      );
      if (!parsedResult.success) {
        debug(`Failed to parse token from ${FRAGMENT_ACCESS_TOKEN_PATH}`);
      }
      if (parsedResult.success) {
        const { created_ms, expires_in } = parsedResult.data;
        if (created_ms + expires_in * 1e3 > Date.now()) {
          debug(
            `Token hasn't expired. Using token from ${FRAGMENT_ACCESS_TOKEN_PATH}`
          );
          return parsedResult.data;
        } else {
          debug(
            `Token in ${FRAGMENT_ACCESS_TOKEN_PATH} is expired. Fetching a new one.`
          );
        }
      }
    }
  } catch (e) {
    debug(`Failed to read token: ${e}`);
  }
};

export {
  DEFAULT_TOKEN_EXPIRATION_MS,
  AccessTokenSchema,
  getToken,
  attemptToCacheToken,
  readUnexpiredAccessToken
};
