"use client";
import { useQuery, useSuspenseQuery, useInfiniteQuery, useSuspenseInfiniteQuery, useQueryClient, useMutation } from '@tanstack/react-query';
import { createApiClient } from '@btst/stack/plugins/client';
import { usePluginOverrides } from '@btst/stack/context';
import { createCMSQueryKeys } from '../../../../../../../plugins/cms/query-keys.mjs';

function isErrorResponse(response) {
  if (typeof response !== "object" || response === null) {
    return false;
  }
  const obj = response;
  return "error" in obj && obj.error !== null && obj.error !== void 0;
}
function toError(error) {
  if (error instanceof Error) {
    return error;
  }
  if (typeof error === "object" && error !== null) {
    const errorObj = error;
    const message = (typeof errorObj.message === "string" ? errorObj.message : null) || (typeof errorObj.error === "string" ? errorObj.error : null) || JSON.stringify(error);
    const err = new Error(message);
    Object.assign(err, error);
    return err;
  }
  return new Error(String(error));
}
const SHARED_QUERY_CONFIG = {
  retry: false,
  refetchOnWindowFocus: false,
  refetchOnMount: false,
  refetchOnReconnect: false,
  staleTime: 1e3 * 60 * 5,
  // 5 minutes
  gcTime: 1e3 * 60 * 10
  // 10 minutes
};
function useContentTypes() {
  const { apiBaseURL, apiBasePath, headers } = usePluginOverrides("cms");
  const client = createApiClient({
    baseURL: apiBaseURL,
    basePath: apiBasePath
  });
  const queries = createCMSQueryKeys(client, headers);
  const baseQuery = queries.cmsTypes.list();
  const { data, isLoading, error, refetch } = useQuery({
    ...baseQuery,
    ...SHARED_QUERY_CONFIG
  });
  return {
    contentTypes: data ?? [],
    isLoading,
    error,
    refetch
  };
}
function useSuspenseContentTypes() {
  const { apiBaseURL, apiBasePath, headers } = usePluginOverrides("cms");
  const client = createApiClient({
    baseURL: apiBaseURL,
    basePath: apiBasePath
  });
  const queries = createCMSQueryKeys(client, headers);
  const baseQuery = queries.cmsTypes.list();
  const { data, refetch, error, isFetching } = useSuspenseQuery({
    ...baseQuery,
    ...SHARED_QUERY_CONFIG
  });
  if (error && !isFetching) {
    throw error;
  }
  return {
    contentTypes: data ?? [],
    refetch
  };
}
function useContentType(slug) {
  const { apiBaseURL, apiBasePath, headers } = usePluginOverrides("cms");
  const client = createApiClient({
    baseURL: apiBaseURL,
    basePath: apiBasePath
  });
  const queries = createCMSQueryKeys(client, headers);
  const baseQuery = queries.cmsTypes.detail(slug);
  const { data, isLoading, error, refetch } = useQuery({
    ...baseQuery,
    ...SHARED_QUERY_CONFIG,
    enabled: !!slug
  });
  return {
    contentType: data ?? null,
    isLoading,
    error,
    refetch
  };
}
function useContent(typeSlug, options = {}) {
  const { apiBaseURL, apiBasePath, headers } = usePluginOverrides("cms");
  const client = createApiClient({
    baseURL: apiBaseURL,
    basePath: apiBasePath
  });
  const queries = createCMSQueryKeys(client, headers);
  const { limit = 10, enabled = true } = options;
  const baseQuery = queries.cmsContent.list({ typeSlug, limit, offset: 0 });
  const {
    data,
    isLoading,
    error,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
    refetch
  } = useInfiniteQuery({
    queryKey: baseQuery.queryKey,
    queryFn: async ({ pageParam = 0 }) => {
      const response = await client("/content/:typeSlug", {
        method: "GET",
        params: { typeSlug },
        query: { limit, offset: pageParam },
        headers
      });
      if (isErrorResponse(response)) {
        throw toError(response.error);
      }
      return response.data;
    },
    ...SHARED_QUERY_CONFIG,
    initialPageParam: 0,
    getNextPageParam: (lastPage, allPages) => {
      if (!lastPage || typeof lastPage !== "object") return void 0;
      const items2 = lastPage?.items;
      if (!Array.isArray(items2) || items2.length < limit) return void 0;
      const loadedCount = (allPages || []).reduce(
        (sum, page) => sum + (Array.isArray(page?.items) ? page.items.length : 0),
        0
      );
      const total2 = lastPage?.total ?? 0;
      if (loadedCount >= total2) return void 0;
      return loadedCount;
    },
    enabled: enabled && !!typeSlug
  });
  const pages = data?.pages;
  const items = pages?.flatMap(
    (page) => Array.isArray(page?.items) ? page.items : []
  ) ?? [];
  const total = pages?.[0]?.total ?? 0;
  return {
    items,
    total,
    isLoading,
    error,
    loadMore: fetchNextPage,
    hasMore: !!hasNextPage,
    isLoadingMore: isFetchingNextPage,
    refetch
  };
}
function useSuspenseContent(typeSlug, options = {}) {
  const { apiBaseURL, apiBasePath, headers } = usePluginOverrides("cms");
  const client = createApiClient({
    baseURL: apiBaseURL,
    basePath: apiBasePath
  });
  const queries = createCMSQueryKeys(client, headers);
  const { limit = 10 } = options;
  const baseQuery = queries.cmsContent.list({ typeSlug, limit, offset: 0 });
  const {
    data,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
    refetch,
    error,
    isFetching
  } = useSuspenseInfiniteQuery({
    queryKey: baseQuery.queryKey,
    queryFn: async ({ pageParam = 0 }) => {
      const response = await client("/content/:typeSlug", {
        method: "GET",
        params: { typeSlug },
        query: { limit, offset: pageParam },
        headers
      });
      if (isErrorResponse(response)) {
        throw toError(response.error);
      }
      return response.data;
    },
    ...SHARED_QUERY_CONFIG,
    initialPageParam: 0,
    getNextPageParam: (lastPage, allPages) => {
      if (!lastPage || typeof lastPage !== "object") return void 0;
      const items2 = lastPage?.items;
      if (!Array.isArray(items2) || items2.length < limit) return void 0;
      const loadedCount = (allPages || []).reduce(
        (sum, page) => sum + (Array.isArray(page?.items) ? page.items.length : 0),
        0
      );
      const total2 = lastPage?.total ?? 0;
      if (loadedCount >= total2) return void 0;
      return loadedCount;
    }
  });
  if (error && !isFetching) {
    throw error;
  }
  const pages = data.pages;
  const items = pages?.flatMap(
    (page) => Array.isArray(page?.items) ? page.items : []
  ) ?? [];
  const total = pages?.[0]?.total ?? 0;
  return {
    items,
    total,
    loadMore: fetchNextPage,
    hasMore: !!hasNextPage,
    isLoadingMore: isFetchingNextPage,
    refetch
  };
}
function useContentItem(typeSlug, id) {
  const { apiBaseURL, apiBasePath, headers } = usePluginOverrides("cms");
  const client = createApiClient({
    baseURL: apiBaseURL,
    basePath: apiBasePath
  });
  const queries = createCMSQueryKeys(client, headers);
  const baseQuery = queries.cmsContent.detail(typeSlug, id);
  const { data, isLoading, error, refetch } = useQuery({
    ...baseQuery,
    ...SHARED_QUERY_CONFIG,
    enabled: !!typeSlug && !!id
  });
  return {
    item: data ?? null,
    isLoading,
    error,
    refetch
  };
}
function useSuspenseContentItem(typeSlug, id) {
  const { apiBaseURL, apiBasePath, headers } = usePluginOverrides("cms");
  const client = createApiClient({
    baseURL: apiBaseURL,
    basePath: apiBasePath
  });
  const queries = createCMSQueryKeys(client, headers);
  const baseQuery = queries.cmsContent.detail(typeSlug, id);
  const { data, refetch, error, isFetching } = useSuspenseQuery({
    ...baseQuery,
    ...SHARED_QUERY_CONFIG
  });
  if (error && !isFetching) {
    throw error;
  }
  return {
    item: data ?? null,
    refetch
  };
}
function useContentItemBySlug(typeSlug, slug) {
  const { apiBaseURL, apiBasePath, headers } = usePluginOverrides("cms");
  const client = createApiClient({
    baseURL: apiBaseURL,
    basePath: apiBasePath
  });
  const queries = createCMSQueryKeys(client, headers);
  const baseQuery = queries.cmsContent.bySlug(typeSlug, slug);
  const { data, isLoading, error, refetch } = useQuery({
    ...baseQuery,
    ...SHARED_QUERY_CONFIG,
    enabled: !!typeSlug && !!slug
  });
  return {
    item: data ?? null,
    isLoading,
    error,
    refetch
  };
}
function useCreateContent(typeSlug) {
  const { refresh, apiBaseURL, apiBasePath, headers } = usePluginOverrides("cms");
  const client = createApiClient({
    baseURL: apiBaseURL,
    basePath: apiBasePath
  });
  const queryClient = useQueryClient();
  const queries = createCMSQueryKeys(client, headers);
  return useMutation({
    mutationKey: [...queries.cmsContent._def, typeSlug, "create"],
    mutationFn: async (data) => {
      const response = await client("@post/content/:typeSlug", {
        method: "POST",
        params: { typeSlug },
        body: data,
        headers
      });
      if (isErrorResponse(response)) {
        throw toError(response.error);
      }
      return response.data;
    },
    onSuccess: async () => {
      await queryClient.invalidateQueries({
        queryKey: queries.cmsContent.list._def
      });
      await queryClient.invalidateQueries({
        queryKey: queries.cmsTypes.list._def
      });
      if (refresh) {
        await refresh();
      }
    }
  });
}
function useUpdateContent(typeSlug) {
  const { refresh, apiBaseURL, apiBasePath, headers } = usePluginOverrides("cms");
  const client = createApiClient({
    baseURL: apiBaseURL,
    basePath: apiBasePath
  });
  const queryClient = useQueryClient();
  const queries = createCMSQueryKeys(client, headers);
  return useMutation({
    mutationKey: [...queries.cmsContent._def, typeSlug, "update"],
    mutationFn: async ({ id, data }) => {
      const response = await client("@put/content/:typeSlug/:id", {
        method: "PUT",
        params: { typeSlug, id },
        body: data,
        headers
      });
      if (isErrorResponse(response)) {
        throw toError(response.error);
      }
      return response.data;
    },
    onSuccess: async (updated) => {
      if (updated) {
        queryClient.setQueryData(
          queries.cmsContent.detail(typeSlug, updated.id).queryKey,
          updated
        );
      }
      await queryClient.invalidateQueries({
        queryKey: queries.cmsContent.list._def
      });
      if (refresh) {
        await refresh();
      }
    }
  });
}
function useDeleteContent(typeSlug) {
  const { refresh, apiBaseURL, apiBasePath, headers } = usePluginOverrides("cms");
  const client = createApiClient({
    baseURL: apiBaseURL,
    basePath: apiBasePath
  });
  const queryClient = useQueryClient();
  const queries = createCMSQueryKeys(client, headers);
  return useMutation({
    mutationKey: [...queries.cmsContent._def, typeSlug, "delete"],
    mutationFn: async (id) => {
      const response = await client("@delete/content/:typeSlug/:id", {
        method: "DELETE",
        params: { typeSlug, id },
        headers
      });
      if (isErrorResponse(response)) {
        throw toError(response.error);
      }
      return response.data;
    },
    onSuccess: async () => {
      await queryClient.invalidateQueries({
        queryKey: queries.cmsContent._def
      });
      await queryClient.invalidateQueries({
        queryKey: queries.cmsTypes.list._def
      });
      if (refresh) {
        await refresh();
      }
    }
  });
}
function useContentItemPopulated(typeSlug, id) {
  const { apiBaseURL, apiBasePath, headers } = usePluginOverrides("cms");
  const client = createApiClient({
    baseURL: apiBaseURL,
    basePath: apiBasePath
  });
  const { data, isLoading, error, refetch } = useQuery({
    queryKey: ["cmsContent", typeSlug, id, "populated"],
    queryFn: async () => {
      const response = await client(
        "/content/:typeSlug/:id/populated",
        {
          method: "GET",
          params: { typeSlug, id },
          headers
        }
      );
      if (isErrorResponse(response)) {
        throw toError(response.error);
      }
      return response.data;
    },
    ...SHARED_QUERY_CONFIG,
    enabled: !!typeSlug && !!id
  });
  return {
    item: data ?? null,
    isLoading,
    error,
    refetch
  };
}
function useSuspenseContentItemPopulated(typeSlug, id) {
  const { apiBaseURL, apiBasePath, headers } = usePluginOverrides("cms");
  const client = createApiClient({
    baseURL: apiBaseURL,
    basePath: apiBasePath
  });
  const { data, refetch, error, isFetching } = useSuspenseQuery({
    queryKey: ["cmsContent", typeSlug, id, "populated"],
    queryFn: async () => {
      const response = await client(
        "/content/:typeSlug/:id/populated",
        {
          method: "GET",
          params: { typeSlug, id },
          headers
        }
      );
      if (isErrorResponse(response)) {
        throw toError(response.error);
      }
      return response.data;
    },
    ...SHARED_QUERY_CONFIG
  });
  if (error && !isFetching) {
    throw error;
  }
  return {
    item: data ?? null,
    refetch
  };
}
function useContentByRelation(typeSlug, fieldName, targetId, options = {}) {
  const { apiBaseURL, apiBasePath, headers } = usePluginOverrides("cms");
  const client = createApiClient({
    baseURL: apiBaseURL,
    basePath: apiBasePath
  });
  const { limit = 20, enabled = true } = options;
  const {
    data,
    isLoading,
    error,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
    refetch
  } = useInfiniteQuery({
    queryKey: ["cmsContent", typeSlug, "by-relation", fieldName, targetId],
    queryFn: async ({ pageParam = 0 }) => {
      const response = await client("/content/:typeSlug/by-relation", {
        method: "GET",
        params: { typeSlug },
        query: { field: fieldName, targetId, limit, offset: pageParam },
        headers
      });
      if (isErrorResponse(response)) {
        throw toError(response.error);
      }
      return response.data;
    },
    ...SHARED_QUERY_CONFIG,
    initialPageParam: 0,
    getNextPageParam: (lastPage, allPages) => {
      if (!lastPage || typeof lastPage !== "object") return void 0;
      const items2 = lastPage?.items;
      if (!Array.isArray(items2) || items2.length < limit) return void 0;
      const loadedCount = (allPages || []).reduce(
        (sum, page) => sum + (Array.isArray(page?.items) ? page.items.length : 0),
        0
      );
      const total2 = lastPage?.total ?? 0;
      if (loadedCount >= total2) return void 0;
      return loadedCount;
    },
    enabled: enabled && !!typeSlug && !!fieldName && !!targetId
  });
  const pages = data?.pages;
  const items = pages?.flatMap(
    (page) => Array.isArray(page?.items) ? page.items : []
  ) ?? [];
  const total = pages?.[0]?.total ?? 0;
  return {
    items,
    total,
    isLoading,
    error,
    loadMore: fetchNextPage,
    hasMore: !!hasNextPage,
    isLoadingMore: isFetchingNextPage,
    refetch
  };
}
function useSuspenseContentByRelation(typeSlug, fieldName, targetId, options = {}) {
  const { apiBaseURL, apiBasePath, headers } = usePluginOverrides("cms");
  const client = createApiClient({
    baseURL: apiBaseURL,
    basePath: apiBasePath
  });
  const { limit = 20 } = options;
  const {
    data,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
    refetch,
    error,
    isFetching
  } = useSuspenseInfiniteQuery({
    queryKey: ["cmsContent", typeSlug, "by-relation", fieldName, targetId],
    queryFn: async ({ pageParam = 0 }) => {
      const response = await client("/content/:typeSlug/by-relation", {
        method: "GET",
        params: { typeSlug },
        query: { field: fieldName, targetId, limit, offset: pageParam },
        headers
      });
      if (isErrorResponse(response)) {
        throw toError(response.error);
      }
      return response.data;
    },
    ...SHARED_QUERY_CONFIG,
    initialPageParam: 0,
    getNextPageParam: (lastPage, allPages) => {
      if (!lastPage || typeof lastPage !== "object") return void 0;
      const items2 = lastPage?.items;
      if (!Array.isArray(items2) || items2.length < limit) return void 0;
      const loadedCount = (allPages || []).reduce(
        (sum, page) => sum + (Array.isArray(page?.items) ? page.items.length : 0),
        0
      );
      const total2 = lastPage?.total ?? 0;
      if (loadedCount >= total2) return void 0;
      return loadedCount;
    }
  });
  if (error && !isFetching) {
    throw error;
  }
  const pages = data.pages;
  const items = pages?.flatMap(
    (page) => Array.isArray(page?.items) ? page.items : []
  ) ?? [];
  const total = pages?.[0]?.total ?? 0;
  return {
    items,
    total,
    loadMore: fetchNextPage,
    hasMore: !!hasNextPage,
    isLoadingMore: isFetchingNextPage,
    refetch
  };
}

export { useContent, useContentByRelation, useContentItem, useContentItemBySlug, useContentItemPopulated, useContentType, useContentTypes, useCreateContent, useDeleteContent, useSuspenseContent, useSuspenseContentByRelation, useSuspenseContentItem, useSuspenseContentItemPopulated, useSuspenseContentTypes, useUpdateContent };
