import axios from 'axios';
import { toast } from 'sonner';
import { emitter } from './MittContext';

const axiosInstance = axios.create({
    withCredentials: true,
    xsrfHeaderName: 'X-XSRF-TOKEN',
    xsrfCookieName: 'XSRF-TOKEN',
});

axiosInstance.interceptors.response.use(
    (response) => response,
    (error) => {
        //console.log(error);
        if (error.response && error.response.status === 500) {
            if (error?.response?.data?.message?.length > 0) {
                toast.error(error.response.data.message + ' Please try again later.');
            }
        }

        if (error.response && error.response.status === 401) {
            //toast.error('You are not logged in. Please login to continue.');

            emitter.emit('401');
        }

        return Promise.reject(error);
    },
);

export default axiosInstance;
