import axios from 'axios';

axios.defaults.withCredentials = true;

// Create an Axios instance
const axiosInstance = axios.create({
    baseURL: 'http://localhost:4040/api/v1',
});

// Intercept request to add token
axiosInstance.interceptors.request.use(
    async (config) => {
        const token = localStorage.getItem('token');
        if (token) {
        config.headers['Authorization'] = `Bearer ${token}`;
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// Intercept response to handle errors
axiosInstance.interceptors.response.use(
    (response) => response,
    async (error) => {
        const originalRequest = error.config;
        // Handle 401 Unauthorized errors (e.g., expired or missing token)
        if (error.response.status === 401) {
            try {
            const response = await axios.post('http://localhost:4040/api/v1/refresh', {}, { withCredentials: true });
            const newToken = response.data.token;
            localStorage.setItem('token', newToken);
            // Retry the original request with the new token
            originalRequest.headers['Authorization'] = `Bearer ${newToken}`;
            return axiosInstance(originalRequest);
            } catch (error) {
            // If refresh fails, log out and redirect to login
            await axios.post('http://localhost:4040/api/v1/logout', {}, { withCredentials: true });
            localStorage.removeItem('token');
            window.location.href = '/login';
            return Promise.reject(error);
            }
        }
        // Handle 403 Forbidden errors (e.g., insufficient permissions)
        if (error.response.status === 403) {
            window.location.href = '/home'; // Redirect to a custom forbidden page or home
            return Promise.reject(error);
        }
        return Promise.reject(error);
    }
);

export default axiosInstance;
