'use strict';

require('../chunk-DGUM43GV.js');
var useSWR = require('swr');
var react = require('react');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var useSWR__default = /*#__PURE__*/_interopDefault(useSWR);

function createUseConfigs(options) {
  const {
    apiBaseUrl = "",
    getAuthToken,
    onUnauthorized,
    dedupingInterval = 6e4,
    revalidateOnFocus = false
  } = options;
  const fetcher = async (url) => {
    const token = await getAuthToken();
    const res = await fetch(apiBaseUrl + url, {
      headers: {
        Authorization: "Bearer " + token,
        "Content-Type": "application/json"
      },
      credentials: "include"
    });
    if (!res.ok) {
      if (res.status === 401) {
        onUnauthorized?.();
        throw new Error("Unauthorized");
      }
      throw new Error("Failed to fetch configs");
    }
    const data = await res.json();
    return data.data;
  };
  return function useConfigs() {
    const {
      data,
      error,
      mutate: mutateConfigs
    } = useSWR__default.default("/api/admin/config", fetcher, {
      // 配置选项
      revalidateOnFocus,
      revalidateOnReconnect: true,
      // 网络重连时重新验证
      dedupingInterval,
      // 缓存去重时间
      errorRetryCount: 3,
      // 错误重试3次
      errorRetryInterval: 5e3,
      // 重试间隔5秒
      shouldRetryOnError: true,
      // 启用错误重试
      // 成功时的回调
      onSuccess: (_data) => {
        console.log("\u2705 Configs loaded from cache or network");
      },
      // 错误时的回调
      onError: (err) => {
        console.error("\u274C Failed to load configs:", err);
      }
    });
    const updateConfigs = react.useCallback(
      async (category, updates) => {
        const token = await getAuthToken();
        mutateConfigs(
          (current) => {
            if (!current) return current;
            return {
              ...current,
              [category]: {
                ...current[category],
                ...Object.entries(updates).reduce((acc, [key, value]) => {
                  acc[key] = {
                    ...current[category]?.[key],
                    value
                  };
                  return acc;
                }, {})
              }
            };
          },
          false
          // 不立即重新验证
        );
        try {
          const res = await fetch(apiBaseUrl + "/api/admin/config/" + category, {
            method: "POST",
            headers: {
              Authorization: "Bearer " + token,
              "Content-Type": "application/json"
            },
            credentials: "include",
            body: JSON.stringify({ configs: updates })
          });
          if (!res.ok) throw new Error("Update failed");
          mutateConfigs();
          return { success: true };
        } catch (error2) {
          mutateConfigs();
          throw error2;
        }
      },
      [mutateConfigs, getAuthToken, apiBaseUrl]
    );
    const refresh = react.useCallback(() => {
      mutateConfigs();
    }, [mutateConfigs]);
    return {
      configs: data,
      isLoading: !error && !data,
      isError: !!error,
      error,
      updateConfigs,
      refresh
    };
  };
}
function prefetchConfigs(apiBaseUrl = "") {
  useSWR.mutate(apiBaseUrl + "/api/admin/config");
}
function invalidateAllConfigs(apiBaseUrl = "") {
  useSWR.mutate(
    (key) => typeof key === "string" && key.startsWith(apiBaseUrl + "/api/admin/config"),
    void 0,
    { revalidate: true }
  );
}

exports.createUseConfigs = createUseConfigs;
exports.invalidateAllConfigs = invalidateAllConfigs;
exports.prefetchConfigs = prefetchConfigs;
//# sourceMappingURL=index.js.map
//# sourceMappingURL=index.js.map