import AsyncStorage from '@react-native-async-storage/async-storage';
import {Alert} from 'react-native';
import RootNavigation from '../navigation/RootNavigation';
import AsyncStorageKeys from '../utils/AsyncStorageKeys';
import AsyncStorageService from '../utils/AsyncStorageService';
import {APP_NAVIGATE_SCREEN} from '../utils/constant';
import {ToastMessage} from '../utils/MessageUtil';
import api from './axios';

const createAPI = () => {
  // const APIInstant = require('axios').default.create()
  const APIInstant = require('axios').default.create();
  //console.log('createAPI', api.getBaseURL());
  APIInstant.defaults.baseURL = api.getBaseURL();
  APIInstant.defaults.timeout = 40000;
  APIInstant.defaults.headers = {'Content-Type': 'application/json'};
  APIInstant.interceptors.request.use(async config => {
    config.headers.Authorization =
      'Bearer ' + (await AsyncStorageService.getToken()) ?? '';
    return config;
  }, Promise.reject);
  APIInstant.interceptors.response.use(async response => {
    const data = response.data;
    if (data && data?.code === 401) {
      ToastMessage({title: 'Notification', message: data?.message});
      await AsyncStorageService.clear().then(() => {
        RootNavigation.navigate(APP_NAVIGATE_SCREEN.LOGIN);
      });
    } else if (data && data.success === false)
      // Alert.alert(' ', data.message)
      console.log('data.message', data.message);
    return response;
  });
  return APIInstant;
};

let axiosClient = createAPI();

/* Support function */
function handleResult(api) {
  return api.then(res => {
    return handleResponse(res.data);
  });
}

function handleResponse(data) {
  if (data && data.success === false) {
    return Promise.reject(new Error(data?.message || 'Co loi xay ra'));
  }
  return Promise.resolve(data);
}
export const ApiClient = {
  get: (url, payload) => handleResult(axiosClient.get(url, payload)),
  post: (url, payload) => handleResult(axiosClient.post(url, payload)),
  put: (url, payload) => handleResult(axiosClient.put(url, payload)),
  path: (url, payload) => handleResult(axiosClient.patch(url, payload)),
  delete: (url, payload) =>
    handleResult(axiosClient.delete(url, {data: payload})),
};
export function refreshApiService() {
  axiosClient = createAPI();
}
