import axios from 'axios';
import { API_URL, APP_VERSION } from '../constants';
import { Platform } from 'react-native';
import { showBanner } from './bannerUtils';

export const request = axios.create({
  baseURL: API_URL,
  timeout: 10000
});

export const setupInterceptors = ({
  showError
}: {
  showError: (message: string, loginNeeded: boolean) => void;
}) => {
  request.interceptors.request.use(
    (config) => {
      config.headers['App-Version'] = APP_VERSION;
      config.headers['Platform'] = Platform.OS;
      return config;
    },
    (error) => {
      return Promise.reject(error);
    }
  );

  request.interceptors.response.use(
    (response) => {
      if (response.data.result === 'ERROR' && response.data.result_description) {
        const showErrorWithDelay = (message: string, requiresLogin: boolean) => {
          setTimeout(() => {
            showError(message, requiresLogin);
          }, 1000);
        };

        if (response.data?.login_needed && response.data.login_needed === 1) {
          showErrorWithDelay(response.data.result_description, true);
          return response;
        }
        showErrorWithDelay(response.data.result_description, false);
      }
      return response;
    },
    (error) => {
      if (error.code === 'ECONNABORTED') {
        error.isTimeout = true;
        showBanner('Slow internet connection!');
        
        return Promise.reject(error);
      } else if (error.message === 'Network Error') {
        return Promise.reject(error);
      }

      showError(error.message, false);

      return Promise.reject(error);
    }
  );
};
