import { useAppConfig } from '@velofex/hooks';
import { RequestClient } from '@velofex/request';

const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD);

function getEnterpriseCode() {
  if (typeof window === 'undefined') {
    return '';
  }

  const searchParams = new URLSearchParams(window.location.search);
  const direct = (searchParams.get('enterpriseCode') ?? '').trim();
  if (direct) {
    return direct;
  }

  // Hash 路由场景: #/path?enterpriseCode=xxx
  const hash = window.location.hash ?? '';
  const idx = hash.indexOf('?');
  if (idx !== -1) {
    const hashParams = new URLSearchParams(hash.slice(idx + 1));
    return (hashParams.get('enterpriseCode') ?? '').trim();
  }
  return '';
}

function getEnterpriseToken() {
  const enterpriseCode = getEnterpriseCode();
  if (!enterpriseCode) {
    return '';
  }
  return localStorage.getItem(`token_${enterpriseCode}`) ?? '';
}

const requestClient = new RequestClient({
  baseURL: apiURL,
});

requestClient.addRequestInterceptor({
  fulfilled: async (config) => {
    const url = config.url ?? '';
    const baseURL = config.baseURL ?? '';
    const isEapiRequest =
      url.startsWith('/eapi') || baseURL.startsWith('/eapi');

    const token = isEapiRequest
      ? (localStorage.getItem('token_a') ?? '')
      : getEnterpriseToken();

    if (token) {
      config.headers = config.headers ?? {};
      config.headers.Authorization = token;
    }
    return config;
  },
});

requestClient.addResponseInterceptor({
  fulfilled: async (response) => {
    return response?.data ?? response;
  },
});

export { requestClient };
