import { mergeQueryKeys, createQueryKeys } from '@lukemorales/query-key-factory';

function handleResponse(response) {
  if (typeof response === "object" && response !== null && "error" in response) {
    const errorResponse = response;
    if (errorResponse.error !== null && errorResponse.error !== void 0) {
      const error = errorResponse.error;
      if (error instanceof Error) {
        throw 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);
        throw new Error(message);
      }
      throw new Error(String(error));
    }
  }
  return response.data;
}
function createAiChatQueryKeys(client, headers) {
  const conversations = createConversationsQueries(client, headers);
  return mergeQueryKeys(conversations);
}
function createConversationsQueries(client, headers) {
  return createQueryKeys("conversations", {
    // List all conversations
    list: () => ({
      // NOTE: query-key-factory already namespaces as:
      // ["conversations", "list", ...queryKey]
      // so we use a stable marker (not "list") to avoid ["...","list","list"].
      queryKey: ["all"],
      queryFn: async () => {
        const response = await client("/chat/conversations", {
          method: "GET",
          headers
        });
        const data = handleResponse(response);
        return data ?? [];
      }
    }),
    // Get single conversation with messages
    detail: (id) => ({
      queryKey: [id],
      queryFn: async () => {
        if (!id) return null;
        const response = await client("/chat/conversations/:id", {
          method: "GET",
          params: { id },
          headers
        });
        return handleResponse(response);
      }
    })
  });
}

export { createAiChatQueryKeys };
