import axios, { AxiosInstance, AxiosRequestConfig, AxiosError } from 'axios';
import { getCookie, deleteCookie } from 'cookies-next';
import { useRouter } from 'next/router';
import { BASE_URI } from '@/helpers/constants';

const authRequest: AxiosInstance = axios.create({
    baseURL: BASE_URI,
});

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

authRequest.interceptors.response.use(
    response => {
        return response;
    },
    (error: AxiosError) => {
        const router = useRouter();
        if (error.response && error.response.status === 401) {
            localStorage.removeItem('token');
            router.push('/login');
        }
        return Promise.reject(error);
    }
);

export default authRequest;
