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

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 useConversations(options = {}) {
  const { apiBaseURL, apiBasePath, headers } = usePluginOverrides("ai-chat");
  const client = createApiClient({
    baseURL: apiBaseURL,
    basePath: apiBasePath
  });
  const { enabled = true } = options;
  const queries = createAiChatQueryKeys(client, headers);
  const listQuery = queries.conversations.list();
  const { data, isLoading, error, refetch } = useQuery({
    ...listQuery,
    ...SHARED_QUERY_CONFIG,
    enabled: enabled && !!client
  });
  return {
    conversations: data ?? [],
    isLoading,
    error,
    refetch
  };
}
function useSuspenseConversations() {
  const { apiBaseURL, apiBasePath, headers } = usePluginOverrides("ai-chat");
  const client = createApiClient({
    baseURL: apiBaseURL,
    basePath: apiBasePath
  });
  const queries = createAiChatQueryKeys(client, headers);
  const listQuery = queries.conversations.list();
  const { data, refetch, error, isFetching } = useSuspenseQuery({
    ...listQuery,
    ...SHARED_QUERY_CONFIG
  });
  if (error && !isFetching) {
    throw error;
  }
  return {
    conversations: data ?? [],
    refetch
  };
}
function useConversation(id, options = {}) {
  const { apiBaseURL, apiBasePath, headers } = usePluginOverrides("ai-chat");
  const client = createApiClient({
    baseURL: apiBaseURL,
    basePath: apiBasePath
  });
  const { enabled = true } = options;
  const queries = createAiChatQueryKeys(client, headers);
  const detailQuery = queries.conversations.detail(id ?? "");
  const { data, isLoading, error, refetch } = useQuery({
    ...detailQuery,
    ...SHARED_QUERY_CONFIG,
    enabled: enabled && !!client && !!id
  });
  return {
    conversation: data || null,
    isLoading,
    error,
    refetch
  };
}
function useSuspenseConversation(id) {
  const { apiBaseURL, apiBasePath, headers } = usePluginOverrides("ai-chat");
  const client = createApiClient({
    baseURL: apiBaseURL,
    basePath: apiBasePath
  });
  const queries = createAiChatQueryKeys(client, headers);
  const detailQuery = queries.conversations.detail(id);
  const { data, refetch, error, isFetching } = useSuspenseQuery({
    ...detailQuery,
    ...SHARED_QUERY_CONFIG
  });
  if (error && !isFetching) {
    throw error;
  }
  return {
    conversation: data || null,
    refetch
  };
}
function useCreateConversation() {
  const { refresh, apiBaseURL, apiBasePath } = usePluginOverrides("ai-chat");
  const client = createApiClient({
    baseURL: apiBaseURL,
    basePath: apiBasePath
  });
  const queryClient = useQueryClient();
  const queries = createAiChatQueryKeys(client);
  return useMutation({
    mutationKey: [...queries.conversations._def, "create"],
    mutationFn: async (data) => {
      const response = await client("@post/chat/conversations", {
        method: "POST",
        body: data
      });
      return response.data;
    },
    onSuccess: async (created) => {
      await queryClient.invalidateQueries({
        queryKey: queries.conversations.list().queryKey
      });
      if (refresh) {
        await refresh();
      }
    }
  });
}
function useRenameConversation() {
  const { refresh, apiBaseURL, apiBasePath } = usePluginOverrides("ai-chat");
  const client = createApiClient({
    baseURL: apiBaseURL,
    basePath: apiBasePath
  });
  const queryClient = useQueryClient();
  const queries = createAiChatQueryKeys(client);
  return useMutation({
    mutationKey: [...queries.conversations._def, "rename"],
    mutationFn: async ({ id, title }) => {
      const response = await client("@put/chat/conversations/:id", {
        method: "PUT",
        params: { id },
        body: { title }
      });
      return response.data;
    },
    onSuccess: async (updated) => {
      if (updated?.id) {
        queryClient.setQueryData(
          queries.conversations.detail(updated.id).queryKey,
          (old) => old ? { ...old, ...updated } : null
        );
      }
      await queryClient.invalidateQueries({
        queryKey: queries.conversations.list().queryKey
      });
      if (refresh) {
        await refresh();
      }
    }
  });
}
function useDeleteConversation() {
  const { refresh, apiBaseURL, apiBasePath } = usePluginOverrides("ai-chat");
  const client = createApiClient({
    baseURL: apiBaseURL,
    basePath: apiBasePath
  });
  const queryClient = useQueryClient();
  const queries = createAiChatQueryKeys(client);
  return useMutation({
    mutationKey: [...queries.conversations._def, "delete"],
    mutationFn: async ({ id }) => {
      const response = await client("@delete/chat/conversations/:id", {
        method: "DELETE",
        params: { id }
      });
      return response.data;
    },
    onSuccess: async (_, { id }) => {
      queryClient.removeQueries({
        queryKey: queries.conversations.detail(id).queryKey
      });
      await queryClient.invalidateQueries({
        queryKey: queries.conversations.list().queryKey
      });
      if (refresh) {
        await refresh();
      }
    }
  });
}

export { useConversation, useConversations, useCreateConversation, useDeleteConversation, useRenameConversation, useSuspenseConversation, useSuspenseConversations };
