import axios, { type AxiosError } from 'axios';
import keycloak from './keycloak';

export const api = axios.create({
  baseURL: '/api',
  headers: {
    'Content-Type': 'application/json',
  },
});

// Interceptor для добавления Authorization header
api.interceptors.request.use(
  async (config) => {
    if (keycloak.token) {
      try {
        await keycloak.updateToken(5);
      } catch {
        void keycloak.login();
        return Promise.reject(new Error('Token refresh failed'));
      }

      config.headers.Authorization = `Bearer ${keycloak.token}`;
    }
    return config;
  },
  (error: unknown) =>
    Promise.reject(error instanceof Error ? error : new Error('Request error')),
);

// Interceptor для обработки 401 ошибок
api.interceptors.response.use(
  (response) => response,
  (error: AxiosError) => {
    if (error.response?.status === 401) {
      void keycloak.login();
    }
    return Promise.reject(error);
  },
);
