import axios from 'axios';
import { isApiErrorCode } from '@thebet365/shared';
import { useAuthStore } from '../stores/auth';

const ACCOUNT_BLOCKED_CODES = new Set([
  'ACCOUNT_SUSPENDED',
  'ACCOUNT_DISABLED',
  'AGENT_ACCOUNT_SUSPENDED',
  'PARENT_AGENT_SUSPENDED',
]);

const api = axios.create({ baseURL: '/api' });

api.interceptors.request.use((config) => {
  const token = localStorage.getItem('token');
  if (token) config.headers.Authorization = `Bearer ${token}`;

  const locale = localStorage.getItem('locale') || 'zh-CN';
  config.headers['X-Locale'] = locale;
  try {
    const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
    if (timeZone) config.headers['X-Time-Zone'] = timeZone;
  } catch {
    // Some WebViews may not expose a time zone; the API falls back to UTC.
  }

  return config;
});

function clearSession() {
  localStorage.removeItem('token');
  localStorage.removeItem('user');
  try {
    useAuthStore().logout();
  } catch {
    // Pinia may not be ready during bootstrap
  }
}

api.interceptors.response.use(
  (res) => res,
  (err) => {
    const status = err.response?.status;
    const url: string = err.config?.url ?? '';
    const isAuthEndpoint = url.includes('/auth/login') || url.includes('/auth/register');
    const code = err.response?.data?.code;
    const blockedAccount =
      typeof code === 'string' && isApiErrorCode(code) && ACCOUNT_BLOCKED_CODES.has(code);

    if (!isAuthEndpoint && (status === 401 || (status === 403 && blockedAccount))) {
      clearSession();
    }
    return Promise.reject(err);
  },
);

export default api;
