"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var makeswift_api_client_exports = {};
__export(makeswift_api_client_exports, {
  configureStore: () => configureStore,
  fetchAPIResource: () => fetchAPIResource,
  getAPIResource: () => getAPIResource,
  getHasAPIResource: () => getHasAPIResource
});
module.exports = __toCommonJS(makeswift_api_client_exports);
var import_toolkit = require("@reduxjs/toolkit");
var APIResources = __toESM(require("./modules/api-resources"));
var LocalizedResourcesMap = __toESM(require("./modules/localized-resources-map"));
var import_actions = require("./actions");
var import_internal = require("./actions/internal");
var import_host_api = require("./host-api");
var import_toolkit2 = require("./toolkit");
var import_api = require("../api");
const reducer = (0, import_toolkit.combineReducers)({
  apiResources: APIResources.reducer,
  localizedResourcesMap: LocalizedResourcesMap.reducer
});
function getLocalizedResourceId(state, locale, resourceId) {
  return LocalizedResourcesMap.getLocalizedResourceId(
    state.localizedResourcesMap,
    locale,
    resourceId
  );
}
function getHasAPIResource(state, resourceType, resourceId, locale) {
  switch (resourceType) {
    case import_api.APIResourceType.LocalizedGlobalElement:
      if (locale == null) {
        console.error(`Attempt to access ${resourceType} ${resourceId} without a locale`);
        return false;
      }
      const localizedId = getLocalizedResourceId(state, locale, resourceId);
      return localizedId != null && APIResources.getHasAPIResource(state.apiResources, resourceType, localizedId, locale);
    default:
      return APIResources.getHasAPIResource(state.apiResources, resourceType, resourceId, locale);
  }
}
function getAPIResource(state, resourceType, resourceId, locale) {
  switch (resourceType) {
    case import_api.APIResourceType.LocalizedGlobalElement:
      if (locale == null) {
        console.error(`Attempt to access ${resourceType} ${resourceId} without a locale`);
        return null;
      }
      const localizedId = getLocalizedResourceId(state, locale, resourceId);
      return localizedId != null ? APIResources.getAPIResource(state.apiResources, resourceType, localizedId, locale) : null;
    default:
      return APIResources.getAPIResource(state.apiResources, resourceType, resourceId, locale);
  }
}
function fetchAPIResource(resourceType, resourceId, fetch, locale) {
  const fetchJson = async (url) => {
    const response = await fetch(url, {
      headers: {
        "Content-Type": "application/json"
      }
    });
    if (response.status === 404)
      return null;
    if (!response.ok)
      throw new Error(response.statusText);
    if (response.headers.get("content-type")?.includes("application/json") !== true) {
      throw new Error(
        `Expected JSON response from "${url}" but got "${response.headers.get("content-type")}"`
      );
    }
    return response.json();
  };
  return async (dispatch, getState) => {
    const state = getState();
    if (getHasAPIResource(state, resourceType, resourceId, locale)) {
      return getAPIResource(state, resourceType, resourceId, locale);
    }
    let resource;
    switch (resourceType) {
      case import_api.APIResourceType.Swatch:
        resource = await fetchJson(`/api/makeswift/swatches/${resourceId}`);
        break;
      case import_api.APIResourceType.File:
        resource = await fetchJson(`/api/makeswift/files/${resourceId}`);
        break;
      case import_api.APIResourceType.Typography:
        resource = await fetchJson(`/api/makeswift/typographies/${resourceId}`);
        break;
      case import_api.APIResourceType.GlobalElement:
        resource = await fetchJson(`/api/makeswift/global-elements/${resourceId}`);
        break;
      case import_api.APIResourceType.LocalizedGlobalElement: {
        if (locale == null)
          throw new Error("Locale is required to fetch LocalizedGlobalElement");
        if (getLocalizedResourceId(state, locale, resourceId) === null) {
          return null;
        }
        resource = await fetchJson(
          `/api/makeswift/localized-global-elements/${resourceId}/${locale}`
        );
        dispatch(
          (0, import_host_api.setLocalizedResourceId)({
            locale,
            resourceId,
            localizedResourceId: resource?.id ?? null
          })
        );
        break;
      }
      case import_api.APIResourceType.PagePathnameSlice: {
        const url = new URL(`/api/makeswift/page-pathname-slices/${resourceId}`, "http://n");
        if (locale != null)
          url.searchParams.set("locale", locale);
        resource = await fetchJson(url.pathname + url.search);
        break;
      }
      case import_api.APIResourceType.Table:
        resource = await fetchJson(`/api/makeswift/tables/${resourceId}`);
        break;
      default:
        resource = null;
    }
    dispatch((0, import_internal.apiResourceFulfilled)(resourceType, resourceId, resource, locale));
    return resource;
  };
}
function defaultLocaleMiddleware(defaultLocale) {
  return (0, import_toolkit2.actionMiddleware)(() => (next) => {
    return (action) => {
      switch (action.type) {
        case import_actions.ActionTypes.CHANGE_API_RESOURCE:
        case import_actions.ActionTypes.EVICT_API_RESOURCE:
        case import_actions.ActionTypes.SET_LOCALIZED_RESOURCE_ID: {
          const { locale } = action.payload;
          return next({
            ...action,
            payload: { ...action.payload, locale: locale ?? defaultLocale }
          });
        }
      }
      return next(action);
    };
  });
}
function configureStore({
  defaultLocale,
  serializedState
}) {
  return (0, import_toolkit.configureStore)({
    reducer,
    preloadedState: {
      apiResources: APIResources.getInitialState(serializedState?.apiResources),
      localizedResourcesMap: LocalizedResourcesMap.getInitialState(
        serializedState?.localizedResourcesMap
      )
    },
    middleware: (getDefaultMiddleware) => getDefaultMiddleware(import_toolkit2.middlewareOptions).concat(defaultLocaleMiddleware(defaultLocale)),
    devTools: (0, import_toolkit2.devToolsConfig)({
      name: `API client store (${(/* @__PURE__ */ new Date()).toISOString()})`,
      actionsDenylist: [
        import_actions.ActionTypes.BUILDER_POINTER_MOVE,
        import_actions.ActionTypes.HANDLE_POINTER_MOVE,
        import_actions.ActionTypes.ELEMENT_FROM_POINT_CHANGE
      ]
    })
  });
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  configureStore,
  fetchAPIResource,
  getAPIResource,
  getHasAPIResource
});
//# sourceMappingURL=makeswift-api-client.js.map