import axios from "axios";


const api = axios.create({
    baseURL: "http://localhost:5079/api",
    headers: {
        'Content-Type': 'application/json'
    }
});

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

api.interceptors.response.use(
    (response) => response,
    (error) => {
        if (error.response && error.response.status === 401) {
            localStorage.removeItem('token');
            if(error.response.request.responseURL.indexOf('user/login') === -1) {
              window.location.href = '/login';
            } else {
              return Promise.reject(error);
            }
        }
        return Promise.reject(error);
    }
)

export default  api;