import getLocaleCS from '@/shared/lib/getLocaleCS';
import axios from 'axios';
import { getLocale } from 'next-intl/server';
import { LanguageRoutes } from '../i18n/types';
import { BASE_URL } from './URLs';

const httpClient = axios.create({
  baseURL: BASE_URL,
  timeout: 10000,
});

httpClient.interceptors.request.use(
  async (config) => {
    let language = LanguageRoutes.RU;

    try {
      if (typeof window === 'undefined') {
        // Serverda ishlayapti
        language = (await getLocale()) as LanguageRoutes;
      } else {
        // Clientda ishlayapti
        language = getLocaleCS() || LanguageRoutes.RU;
      }
    } catch (e) {
      console.log('Locale olishda xato:', e);
    }

    config.headers['Accept-Language'] = language;

    return config;
  },
  (error) => Promise.reject(error),
);

export default httpClient;
