import axios from 'axios';
import { API_URL, APP_VERSION } from '../constants';
import { Platform } from 'react-native';
import { showBanner } from './bannerUtils';
import { useErrorStore } from 'src/stores/errorStore';
import { attachTelemetryInterceptors } from './telemetry';

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

attachTelemetryInterceptors(request);
attachTelemetryInterceptors(axios);


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

      if (config.data instanceof FormData) {
        config.timeout = 0;
      }

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

  request.interceptors.response.use(
    (response) => {
      const { isErrorShown, setErrorShown } = useErrorStore.getState();

      if (response.data.result === 'ERROR' && response.data.result_description) {
        const showErrorWithDelay = (
          message: string,
          requiresLogin: boolean,
          requiresAuth: boolean,
          requiresPremium: boolean = false
        ) => {
          if (!isErrorShown) {
            setErrorShown(true);
            setTimeout(() => {
              showError(message, requiresLogin, requiresAuth, requiresPremium);
            }, 1000);
          }
        };

        if (response.data?.login_needed && response.data.login_needed === 1) {
          showErrorWithDelay(response.data.result_description, true, false);
          return response;
        } else if (
          response.data.result_description ===
          'Only authenticated users are allowed to send messages.'
        ) {
          showErrorWithDelay(response.data.result_description, false, true);
          return response;
        } else if (response.data?.premium_needed && response.data.premium_needed === 1) {
          showErrorWithDelay(response.data.result_description, false, false, true);
          return response;
        }
        showErrorWithDelay(response.data.result_description, false, false);
      }
      return response;
    },
    (error) => {
      const { isErrorShown, setErrorShown } = useErrorStore.getState();

      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);
      }

      const shortUrl = error.config.url
        ? error.config.url?.split('/')?.filter(Boolean)?.pop()
        : 'Unknown URL';

      if (!isErrorShown) {
        setErrorShown(true);
        showError(`${error.message} (${shortUrl})`, false, false, false);
      }

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