import axios, { AxiosInstance, InternalAxiosRequestConfig, AxiosResponse } from 'axios';
import { BASE_URL } from '@/helpers/constants';

const myAxios: AxiosInstance = axios.create({
    baseURL: BASE_URL,
    timeout: 10000,
});

myAxios.interceptors.request.use(
    (config: InternalAxiosRequestConfig): InternalAxiosRequestConfig => {
        const token = localStorage.getItem('token');
        if (token) {
            config.headers = config.headers || {};
            config.headers['Authorization'] = `Bearer ${token}`;
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

myAxios.interceptors.response.use(
    (response: AxiosResponse) => {
        return response.data;
    },
    error => {
        // if (error.response?.status === 401) {
        //     localStorage.removeItem('token');
        //     window.location.href = '/';
        // }
        return Promise.reject(error);
    }
);

export default myAxios;
