"use client";
'use strict';

const reactQuery = require('@tanstack/react-query');
const client = require('@btst/stack/plugins/client');
const context = require('@btst/stack/context');
const plugins_formBuilder_queryKeys = require('../../../../../../../plugins/form-builder/query-keys.cjs');

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 useForms(options = {}) {
  const { apiBaseURL, apiBasePath, headers } = context.usePluginOverrides("form-builder");
  const client$1 = client.createApiClient({
    baseURL: apiBaseURL,
    basePath: apiBasePath
  });
  const queries = plugins_formBuilder_queryKeys.createFormBuilderQueryKeys(client$1, headers);
  const { status, limit = 20, enabled = true } = options;
  const baseQuery = queries.forms.list({ status, limit, offset: 0 });
  const {
    data,
    isLoading,
    error,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
    refetch
  } = reactQuery.useInfiniteQuery({
    queryKey: baseQuery.queryKey,
    queryFn: async ({ pageParam = 0 }) => {
      const response = await client$1("/forms", {
        method: "GET",
        query: { status, 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 items = lastPage?.items;
      if (!Array.isArray(items) || items.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
  });
  const pages = data?.pages;
  const forms = pages?.flatMap(
    (page) => Array.isArray(page?.items) ? page.items : []
  ) ?? [];
  const total = pages?.[0]?.total ?? 0;
  return {
    forms,
    total,
    isLoading,
    error,
    loadMore: fetchNextPage,
    hasMore: !!hasNextPage,
    isLoadingMore: isFetchingNextPage,
    refetch
  };
}
function useSuspenseForms(options = {}) {
  const { apiBaseURL, apiBasePath, headers } = context.usePluginOverrides("form-builder");
  const client$1 = client.createApiClient({
    baseURL: apiBaseURL,
    basePath: apiBasePath
  });
  const queries = plugins_formBuilder_queryKeys.createFormBuilderQueryKeys(client$1, headers);
  const { status, limit = 20 } = options;
  const baseQuery = queries.forms.list({ status, limit, offset: 0 });
  const {
    data,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
    refetch,
    error,
    isFetching
  } = reactQuery.useSuspenseInfiniteQuery({
    queryKey: baseQuery.queryKey,
    queryFn: async ({ pageParam = 0 }) => {
      const response = await client$1("/forms", {
        method: "GET",
        query: { status, 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 items = lastPage?.items;
      if (!Array.isArray(items) || items.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 forms = pages?.flatMap(
    (page) => Array.isArray(page?.items) ? page.items : []
  ) ?? [];
  const total = pages?.[0]?.total ?? 0;
  return {
    forms,
    total,
    loadMore: fetchNextPage,
    hasMore: !!hasNextPage,
    isLoadingMore: isFetchingNextPage,
    refetch
  };
}
function useFormById(id) {
  const { apiBaseURL, apiBasePath, headers } = context.usePluginOverrides("form-builder");
  const client$1 = client.createApiClient({
    baseURL: apiBaseURL,
    basePath: apiBasePath
  });
  const queries = plugins_formBuilder_queryKeys.createFormBuilderQueryKeys(client$1, headers);
  const baseQuery = queries.forms.byId(id);
  const { data, isLoading, error, refetch } = reactQuery.useQuery({
    ...baseQuery,
    ...SHARED_QUERY_CONFIG,
    enabled: !!id
  });
  return {
    form: data ?? null,
    isLoading,
    error,
    refetch
  };
}
function useSuspenseFormById(id) {
  const { apiBaseURL, apiBasePath, headers } = context.usePluginOverrides("form-builder");
  const client$1 = client.createApiClient({
    baseURL: apiBaseURL,
    basePath: apiBasePath
  });
  const queries = plugins_formBuilder_queryKeys.createFormBuilderQueryKeys(client$1, headers);
  const baseQuery = queries.forms.byId(id);
  const { data, refetch, error, isFetching } = reactQuery.useSuspenseQuery({
    ...baseQuery,
    ...SHARED_QUERY_CONFIG
  });
  if (error && !isFetching) {
    throw error;
  }
  return {
    form: data ?? null,
    refetch
  };
}
function useFormBySlug(slug) {
  const { apiBaseURL, apiBasePath, headers } = context.usePluginOverrides("form-builder");
  const client$1 = client.createApiClient({
    baseURL: apiBaseURL,
    basePath: apiBasePath
  });
  const queries = plugins_formBuilder_queryKeys.createFormBuilderQueryKeys(client$1, headers);
  const baseQuery = queries.forms.bySlug(slug);
  const { data, isLoading, error, refetch } = reactQuery.useQuery({
    ...baseQuery,
    ...SHARED_QUERY_CONFIG,
    enabled: !!slug
  });
  return {
    form: data ?? null,
    isLoading,
    error,
    refetch
  };
}
function useSuspenseFormBySlug(slug) {
  const { apiBaseURL, apiBasePath, headers } = context.usePluginOverrides("form-builder");
  const client$1 = client.createApiClient({
    baseURL: apiBaseURL,
    basePath: apiBasePath
  });
  const queries = plugins_formBuilder_queryKeys.createFormBuilderQueryKeys(client$1, headers);
  const baseQuery = queries.forms.bySlug(slug);
  const { data, refetch, error, isFetching } = reactQuery.useSuspenseQuery({
    ...baseQuery,
    ...SHARED_QUERY_CONFIG
  });
  if (error && !isFetching) {
    throw error;
  }
  return {
    form: data ?? null,
    refetch
  };
}
function useCreateForm() {
  const { refresh, apiBaseURL, apiBasePath, headers } = context.usePluginOverrides("form-builder");
  const client$1 = client.createApiClient({
    baseURL: apiBaseURL,
    basePath: apiBasePath
  });
  const queryClient = reactQuery.useQueryClient();
  const queries = plugins_formBuilder_queryKeys.createFormBuilderQueryKeys(client$1, headers);
  return reactQuery.useMutation({
    mutationKey: [...queries.forms._def, "create"],
    mutationFn: async (data) => {
      const response = await client$1("@post/forms", {
        method: "POST",
        body: data,
        headers
      });
      if (isErrorResponse(response)) {
        throw toError(response.error);
      }
      return response.data;
    },
    onSuccess: async () => {
      await queryClient.invalidateQueries({
        queryKey: queries.forms._def
      });
      if (refresh) {
        await refresh();
      }
    }
  });
}
function useUpdateForm() {
  const { refresh, apiBaseURL, apiBasePath, headers } = context.usePluginOverrides("form-builder");
  const client$1 = client.createApiClient({
    baseURL: apiBaseURL,
    basePath: apiBasePath
  });
  const queryClient = reactQuery.useQueryClient();
  const queries = plugins_formBuilder_queryKeys.createFormBuilderQueryKeys(client$1, headers);
  return reactQuery.useMutation({
    mutationKey: [...queries.forms._def, "update"],
    mutationFn: async ({ id, data }) => {
      const response = await client$1("@put/forms/:id", {
        method: "PUT",
        params: { id },
        body: data,
        headers
      });
      if (isErrorResponse(response)) {
        throw toError(response.error);
      }
      return response.data;
    },
    onSuccess: async (updated) => {
      if (updated) {
        queryClient.setQueryData(
          queries.forms.byId(updated.id).queryKey,
          updated
        );
        queryClient.setQueryData(
          queries.forms.bySlug(updated.slug).queryKey,
          updated
        );
      }
      await queryClient.invalidateQueries({
        queryKey: queries.forms._def
      });
      if (refresh) {
        await refresh();
      }
    }
  });
}
function useDeleteForm() {
  const { refresh, apiBaseURL, apiBasePath, headers } = context.usePluginOverrides("form-builder");
  const client$1 = client.createApiClient({
    baseURL: apiBaseURL,
    basePath: apiBasePath
  });
  const queryClient = reactQuery.useQueryClient();
  const queries = plugins_formBuilder_queryKeys.createFormBuilderQueryKeys(client$1, headers);
  return reactQuery.useMutation({
    mutationKey: [...queries.forms._def, "delete"],
    mutationFn: async (id) => {
      const response = await client$1("@delete/forms/:id", {
        method: "DELETE",
        params: { id },
        headers
      });
      if (isErrorResponse(response)) {
        throw toError(response.error);
      }
      return response.data;
    },
    onSuccess: async () => {
      await queryClient.invalidateQueries({
        queryKey: queries.forms._def
      });
      if (refresh) {
        await refresh();
      }
    }
  });
}
function useSubmitForm(slug) {
  const { apiBaseURL, apiBasePath, headers } = context.usePluginOverrides("form-builder");
  const client$1 = client.createApiClient({
    baseURL: apiBaseURL,
    basePath: apiBasePath
  });
  const queries = plugins_formBuilder_queryKeys.createFormBuilderQueryKeys(client$1, headers);
  return reactQuery.useMutation({
    mutationKey: [...queries.forms._def, slug, "submit"],
    mutationFn: async ({ data }) => {
      const response = await client$1("@post/forms/:slug/submit", {
        method: "POST",
        params: { slug },
        body: { data },
        headers
      });
      if (isErrorResponse(response)) {
        throw toError(response.error);
      }
      return response.data;
    }
  });
}
function useSubmissions(formId, options = {}) {
  const { apiBaseURL, apiBasePath, headers } = context.usePluginOverrides("form-builder");
  const client$1 = client.createApiClient({
    baseURL: apiBaseURL,
    basePath: apiBasePath
  });
  const queries = plugins_formBuilder_queryKeys.createFormBuilderQueryKeys(client$1, headers);
  const { limit = 20, enabled = true } = options;
  const baseQuery = queries.formSubmissions.list({
    formId,
    limit,
    offset: 0
  });
  const {
    data,
    isLoading,
    error,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
    refetch
  } = reactQuery.useInfiniteQuery({
    queryKey: baseQuery.queryKey,
    queryFn: async ({ pageParam = 0 }) => {
      const response = await client$1("/forms/:formId/submissions", {
        method: "GET",
        params: { formId },
        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 items = lastPage?.items;
      if (!Array.isArray(items) || items.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 && !!formId
  });
  const pages = data?.pages;
  const submissions = pages?.flatMap(
    (page) => Array.isArray(page?.items) ? page.items : []
  ) ?? [];
  const total = pages?.[0]?.total ?? 0;
  return {
    submissions,
    total,
    isLoading,
    error,
    loadMore: fetchNextPage,
    hasMore: !!hasNextPage,
    isLoadingMore: isFetchingNextPage,
    refetch
  };
}
function useSuspenseSubmissions(formId, options = {}) {
  const { apiBaseURL, apiBasePath, headers } = context.usePluginOverrides("form-builder");
  const client$1 = client.createApiClient({
    baseURL: apiBaseURL,
    basePath: apiBasePath
  });
  const queries = plugins_formBuilder_queryKeys.createFormBuilderQueryKeys(client$1, headers);
  const { limit = 20 } = options;
  const baseQuery = queries.formSubmissions.list({
    formId,
    limit,
    offset: 0
  });
  const {
    data,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
    refetch,
    error,
    isFetching
  } = reactQuery.useSuspenseInfiniteQuery({
    queryKey: baseQuery.queryKey,
    queryFn: async ({ pageParam = 0 }) => {
      const response = await client$1("/forms/:formId/submissions", {
        method: "GET",
        params: { formId },
        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 items = lastPage?.items;
      if (!Array.isArray(items) || items.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 submissions = pages?.flatMap(
    (page) => Array.isArray(page?.items) ? page.items : []
  ) ?? [];
  const total = pages?.[0]?.total ?? 0;
  return {
    submissions,
    total,
    loadMore: fetchNextPage,
    hasMore: !!hasNextPage,
    isLoadingMore: isFetchingNextPage,
    refetch
  };
}
function useDeleteSubmission(formId) {
  const { refresh, apiBaseURL, apiBasePath, headers } = context.usePluginOverrides("form-builder");
  const client$1 = client.createApiClient({
    baseURL: apiBaseURL,
    basePath: apiBasePath
  });
  const queryClient = reactQuery.useQueryClient();
  const queries = plugins_formBuilder_queryKeys.createFormBuilderQueryKeys(client$1, headers);
  return reactQuery.useMutation({
    mutationKey: [...queries.formSubmissions._def, formId, "delete"],
    mutationFn: async (subId) => {
      const response = await client$1(
        "@delete/forms/:formId/submissions/:subId",
        {
          method: "DELETE",
          params: { formId, subId },
          headers
        }
      );
      if (isErrorResponse(response)) {
        throw toError(response.error);
      }
      return response.data;
    },
    onSuccess: async () => {
      await queryClient.invalidateQueries({
        queryKey: queries.formSubmissions._def
      });
      if (refresh) {
        await refresh();
      }
    }
  });
}

exports.useCreateForm = useCreateForm;
exports.useDeleteForm = useDeleteForm;
exports.useDeleteSubmission = useDeleteSubmission;
exports.useFormById = useFormById;
exports.useFormBySlug = useFormBySlug;
exports.useForms = useForms;
exports.useSubmissions = useSubmissions;
exports.useSubmitForm = useSubmitForm;
exports.useSuspenseFormById = useSuspenseFormById;
exports.useSuspenseFormBySlug = useSuspenseFormBySlug;
exports.useSuspenseForms = useSuspenseForms;
exports.useSuspenseSubmissions = useSuspenseSubmissions;
exports.useUpdateForm = useUpdateForm;
