import { useQuery } from '@tanstack/react-query';

import { chatQueryKeys } from '../chat-query-keys';
import { chatApi, type PostGetChatsListReturn } from '../chat-api';

import type { BaseAxiosError } from '../../../../types';
import { storage, StoreType } from 'src/storage';

export const usePostGetChatsListQuery = (token: string, archive: 0 | 1, enabled: boolean) => {
  return useQuery<PostGetChatsListReturn, BaseAxiosError>({
    queryKey: chatQueryKeys.getChatsList(token, archive),
    queryFn: async () => {
      const response = await chatApi.getChatsList(token, archive);
      storage.set('chats', JSON.stringify(response.data.conversations));
      return response.data;
    },
    enabled,
    initialData: () => {
      try {
        const storedChats = storage.get('chats', StoreType.STRING) as string;
        return storedChats
          ? ({ conversations: JSON.parse(storedChats), result: 'OK' } as PostGetChatsListReturn)
          : undefined;
      } catch {
        return undefined;
      }
    }
  });
};
