import { QueryClient } from '@kevisual/query';
import { modal } from './redirect-to-login';
import { create } from 'zustand';
import { message } from 'antd';
export const query = new QueryClient();
query.beforeRequest = async (config) => {
  if (config.headers) {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers['Authorization'] = 'Bearer ' + token;
    }
  }
  return config;
};
query.afterResponse = async (res) => {
  if (res.code === 401) {
    modal.setOpen(true);
  }
  if (res.code === 403) {
    if (!res?.message) {
      message.error('Unauthorized');
    }
  }
  return res;
};
export const request = query.post;

export const ws = query.qws.ws;
type Store = {
  connected: boolean;
  setConnected: (connected: boolean) => void;
};
export const useStore = create<Store>((set) => ({
  connected: false,
  setConnected: (connected) => set({ connected }),
}));

// 当连接成功时
ws.onopen = () => {
  console.log('Connected to WebSocket server');
  useStore.getState().setConnected(true);
};

// 处理 WebSocket 关闭
ws.onclose = () => {
  console.log('Disconnected from WebSocket server');
};
