import axios, { AxiosAdapter, type AxiosResponse } from 'axios';
// eslint-disable-next-line import/extensions
import adapter from 'axios/lib/adapters/xhr.js';

const cache = new Map();
const EXPIRATION_TIME_MS = 10 * 60 * 1000; // 10 minutes

const cacheAdapterEnhancer: AxiosAdapter = (config) => {
  const { url, method } = config;
  const cacheKey = JSON.stringify({ url, method });

  if (cache.has(cacheKey)) {
    const cachedResult = cache.get(cacheKey);
    if (Date.now() - cachedResult.timestamp < EXPIRATION_TIME_MS) {
      if (cachedResult.error) {
        return Promise.reject(cachedResult.error);
      }

      return Promise.resolve({ headers: cachedResult.headers });
    }

    cache.delete(cacheKey);
  }

  return adapter(config)
    .then((response: AxiosResponse) => {
      // cache headers
      cache.set(cacheKey, { headers: response.headers, timestamp: Date.now() });
      return response;
    })
    .catch((error: unknown) => {
      // cache error
      cache.set(cacheKey, { error, timestamp: Date.now() });
      throw error;
    });
};

const instance = axios.create({
  adapter: cacheAdapterEnhancer,
  timeout: 5000,
});

export default instance;
