import { debounce } from "@scalar/helpers/general/debounce";
import { authStorage, clientStorage } from "../helpers/storage.js";
const persistencePlugin = ({
  debounceDelay = 500,
  maxWait = 1e4,
  prefix = ""
}) => {
  const { execute } = debounce({ delay: debounceDelay, maxWait });
  const authPersistence = authStorage();
  const clientPersistence = clientStorage();
  const getPrefix = () => {
    if (typeof prefix === "string") {
      return prefix;
    }
    return prefix();
  };
  return {
    hooks: {
      /**
       * Handles all workspace state change events.
       * Each write is debounced by a key to prevent frequent writes for the same entity.
       */
      onWorkspaceStateChanges(event) {
        if (event.type === "meta") {
          const defaultClient = event.value["x-scalar-default-client"];
          if (defaultClient !== void 0) {
            execute("x-scalar-default-client", () => clientPersistence.set(defaultClient));
          }
          return;
        }
        if (event.type === "documents") {
          const { path, value: document } = event;
          const { securitySchemes = {} } = document.components ?? {};
          if (path[0] === "components" && path[1] === "securitySchemes") {
            execute("x-scalar-security-schemes", () => authPersistence.setSchemas(getPrefix(), securitySchemes));
          }
          const selectedSecurity = document["x-scalar-selected-security"];
          if (path[0] === "x-scalar-selected-security" && selectedSecurity) {
            execute(
              "x-scalar-selected-security-schemes",
              () => authPersistence.setSelectedSchemes(getPrefix(), {
                "x-scalar-selected-security": selectedSecurity
              })
            );
          }
        }
        return;
      }
    }
  };
};
export {
  persistencePlugin
};
