import '../chunk-BJTO5JO5.mjs';
import useSWR, { mutate } from 'swr';
import { useCallback } from 'react';

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("/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 = 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 = useCallback(() => {
      mutateConfigs();
    }, [mutateConfigs]);
    return {
      configs: data,
      isLoading: !error && !data,
      isError: !!error,
      error,
      updateConfigs,
      refresh
    };
  };
}
function prefetchConfigs(apiBaseUrl = "") {
  mutate(apiBaseUrl + "/api/admin/config");
}
function invalidateAllConfigs(apiBaseUrl = "") {
  mutate(
    (key) => typeof key === "string" && key.startsWith(apiBaseUrl + "/api/admin/config"),
    void 0,
    { revalidate: true }
  );
}

export { createUseConfigs, invalidateAllConfigs, prefetchConfigs };
//# sourceMappingURL=index.mjs.map
//# sourceMappingURL=index.mjs.map