import axios from 'axios';
import Cookies from 'js-cookie';

export const COOKIE_NAME = 'jsession';

export const $api = axios.create({
  baseURL: process.env.NEXT_PUBLIC_API_HOST || 'https://back.v1techprod.ru'
});

export const $proxyapi = axios.create({
  baseURL: '/api/proxy',
});

$api.interceptors.request.use(function (req) {
  const params = req.url?.includes("?") ? new URLSearchParams(req.url?.split('?').at(-1)) : new URLSearchParams();

  if (params.has('jsession')) {
    params.set('jsession', Cookies.get(COOKIE_NAME)!);
  }

  req.url = req.url?.split('?')[0] + '?' + params.toString();

  return req;
});

$api.interceptors.response.use(
  function (response) {
    const responseData = response.data as { message: string; result: number; key?: string };
    if ((responseData?.result === 5 && responseData?.message === 'Session does not exist!')) {
      window.location.href = '/login';
      Cookies.remove(COOKIE_NAME);
      // Проверка на истёкший срок жизни токена
      throw {
        status: 401,
        message: 'UnAuthorized',
      };
    }
    return response;
  },
  function (error) {
    if (error.response.status === 401) {
      Cookies.remove(COOKIE_NAME);
      return (window.location.href = '/login');
    }

    throw error;
  },
);


$proxyapi.interceptors.response.use(
  function (response) {
    return response;
  },
  function (error) {
    if (error.response.status === 401) {
      Cookies.remove(COOKIE_NAME);
      return (window.location.href = '/login');
    }

    throw error;
  },
);
