import { useMemo } from 'react';
import { COMMONINFO_KEY, TOKEN_KEY, USERINFO_KEY } from '@common/constants';
import { useCopilot } from 'react-native-copilot';
import { getAllKeys, removeAllItems } from '@common/StorageHelper.ts';
import { useAuth } from '@common/contexts/useAuth.ts';

/**
 * @description: 处理退出登录的 hook，可以合并处理退出登录时的一些操作
 */
const useLogout = (): {
  actions: {
    logout: () => Promise<void>;
  };
} => {
  const {
    actions: { logout },
  } = useAuth();

  const { stop } = useCopilot();

  const actions = useMemo(
    () => ({
      logout: async () => {
        // ImManager.getInstance().logout();
        // PushManager.getInstance().logout();

        // 退出登录将旧模块中的内容清空
        // --- 这部分内容等旧模块不再使用后就可以删除了 ---
        const keys = await getAllKeys();
        console.log('>>>>>>>>', keys);
        // 保留的 key
        const keysToKeep = [
          COMMONINFO_KEY,
          TOKEN_KEY,
          USERINFO_KEY,
          'follow_first',
        ];
        // 过滤掉需要保留的 key
        const keysToDelete = keys.filter(key => !keysToKeep.includes(key));
        // 删除剩余的 key
        await removeAllItems(keysToDelete);
        // --- 这部分内容等旧模块不再使用后就可以删除了 ---

        stop().catch(() => {
          return;
        });
        await logout();
      },
    }),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [logout],
  );

  return { actions: actions };
};

export { useLogout };
