/* eslint-disable import/no-unresolved */

import { ACCESS_TOKEN, REFRESH_TOKEN } from "@/lib/data";

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


export const BackUrl = import.meta.env.VITE_API_URL

const access_token: string = Cookies.get(ACCESS_TOKEN) || "";

const apiService = axios.create({
  baseURL: BackUrl,
  headers: {
    Authorization: access_token ? `Bearer ${access_token}` : "dsqd"
    // "X-API-Key": "sdk_live_TeeZGyvg34H-nIR7tBhyiemAfIV0MbT2HQ1BzG9bofE"
  }
})


// Interceptor pour capturer les erreurs et gérer le refresh token
apiService.interceptors.response.use(
  response => response,
  async error => {
    if (!error.response) {
      throw new Error('Network Error');
    }
    // Si le token est expiré (401), tente de le rafraîchir
    if (error.response.status === 401) {
      const refreshToken = Cookies.get(REFRESH_TOKEN);
      if (refreshToken) {
        try {
          const res = await axios.post(
            `${BackUrl}/auth/refresh`,
            { refresh_token: refreshToken }
          );

          if (res.data && res.data.success && res.data.data.access_token) {
            Cookies.set(ACCESS_TOKEN, res.data.data.access_token);
            error.config.headers.Authorization = `Bearer ${res.data.data.access_token}`;
            return apiService.request(error.config);
          }
          // eslint-disable-next-line @typescript-eslint/no-unused-vars
        } catch (refreshErr) {
          Cookies.remove(ACCESS_TOKEN);
          Cookies.remove(REFRESH_TOKEN);
        }
      }
    }
    return Promise.reject(error);
  }
);




// Interceptor pour capturer les erreurs
apiService.interceptors.response.use(
  response => response,
  error => {
    if (!error.response) {
      throw new Error('Network Error');
    }
    return Promise.reject(error);
  }
)

apiService.interceptors.request.use(
  request => {
    const access_token: string = Cookies.get(ACCESS_TOKEN) || "";

    // Assurer que le token est présent et valide
    if (access_token) {
      request.headers.Authorization = `Bearer ${access_token}`;
    }
    return request;
  },
  error => {
    // Gérer les erreurs d'intercepteur
    return Promise.reject(error);
  }
);


export default apiService

