import axios from 'axios';

export const API_BASE_URL = 'https://api.hoyidata.com/aura/v1';
const APP_BASE = (import.meta.env.BASE_URL || '/').replace(/\/$/, '');
export const withAppBase = (path: string) => `${APP_BASE}${path.startsWith('/') ? path : `/${path}`}`;
export const withApiBase = (path: string) => `${API_BASE_URL}${path.startsWith('/') ? path : `/${path}`}`;
const isMockAuth = () => typeof localStorage !== 'undefined' && localStorage.getItem('mock-auth') === '1';

export const api = axios.create({
  baseURL: API_BASE_URL,
  timeout: 90000,
  withCredentials: true
});

api.interceptors.response.use(
  (r) => r,
  (err) => {
    const isLoginPage = location.pathname === '/login' || location.pathname === withAppBase('/login');
    if (err?.response?.status === 401 && !isLoginPage && !isMockAuth()) {
      const next = encodeURIComponent(location.pathname + location.search);
      location.href = `${withAppBase('/login')}?next=${next}`;
    }
    return Promise.reject(err);
  }
);

