import {
  configureStore as configureReduxStore,
  combineReducers
} from "@reduxjs/toolkit";
import * as APIResources from "./modules/api-resources";
import * as LocalizedResourcesMap from "./modules/localized-resources-map";
import { ActionTypes } from "./actions";
import { apiResourceFulfilled } from "./actions/internal";
import { setLocalizedResourceId } from "./host-api";
import { actionMiddleware, middlewareOptions, devToolsConfig } from "./toolkit";
import {
  APIResourceType
} from "../api";
const reducer = 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 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 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 APIResourceType.Swatch:
        resource = await fetchJson(`/api/makeswift/swatches/${resourceId}`);
        break;
      case APIResourceType.File:
        resource = await fetchJson(`/api/makeswift/files/${resourceId}`);
        break;
      case APIResourceType.Typography:
        resource = await fetchJson(`/api/makeswift/typographies/${resourceId}`);
        break;
      case APIResourceType.GlobalElement:
        resource = await fetchJson(`/api/makeswift/global-elements/${resourceId}`);
        break;
      case 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(
          setLocalizedResourceId({
            locale,
            resourceId,
            localizedResourceId: resource?.id ?? null
          })
        );
        break;
      }
      case 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 APIResourceType.Table:
        resource = await fetchJson(`/api/makeswift/tables/${resourceId}`);
        break;
      default:
        resource = null;
    }
    dispatch(apiResourceFulfilled(resourceType, resourceId, resource, locale));
    return resource;
  };
}
function defaultLocaleMiddleware(defaultLocale) {
  return actionMiddleware(() => (next) => {
    return (action) => {
      switch (action.type) {
        case ActionTypes.CHANGE_API_RESOURCE:
        case ActionTypes.EVICT_API_RESOURCE:
        case 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 configureReduxStore({
    reducer,
    preloadedState: {
      apiResources: APIResources.getInitialState(serializedState?.apiResources),
      localizedResourcesMap: LocalizedResourcesMap.getInitialState(
        serializedState?.localizedResourcesMap
      )
    },
    middleware: (getDefaultMiddleware) => getDefaultMiddleware(middlewareOptions).concat(defaultLocaleMiddleware(defaultLocale)),
    devTools: devToolsConfig({
      name: `API client store (${(/* @__PURE__ */ new Date()).toISOString()})`,
      actionsDenylist: [
        ActionTypes.BUILDER_POINTER_MOVE,
        ActionTypes.HANDLE_POINTER_MOVE,
        ActionTypes.ELEMENT_FROM_POINT_CHANGE
      ]
    })
  });
}
export {
  configureStore,
  fetchAPIResource,
  getAPIResource,
  getHasAPIResource
};
//# sourceMappingURL=makeswift-api-client.js.map