import axios from "axios"
const api = axios.create({
    baseURL: process.env.VUE_APP_BASE_URL,
    clientId : process.env.VUE_APP_CLIENT_ID,
    clientSecret : process.env.VUE_APP_CLIENT_SECRET,
    headers:{
        "Content-Type":"application/json"
    }
})

api.interceptors.request.use(
    config =>{
        const token = localStorage.getItem('token')
        console.log(token)
        if(token){
            config.headers.Authorization = `Bearer ${token}`
        }
        return config
    }
)

api.interceptors.response.use(
    response => response,
    async error => {
        if(error.response && error.response.status === 401){
            const refresh_token = localStorage.getItem('refresh_token')
            if(refresh_token){
                try {
                const res = await axios.post(`${this.baseURL}` + "/oauth/token/refresh/", {
                    refresh: refresh_token,
                });
                
                localStorage.setItem("access_token", res.data.access);
                error.config.headers.Authorization = `Bearer ${res.data.access}`;
                return api.request(error.config);
                } catch (refreshError) {
                // jika refresh juga gagal, logout
                localStorage.removeItem("access_token");
                localStorage.removeItem("refresh_token");
                window.location = "/login";
                }
            }
            localStorage.removeItem('token')
            window.location.href = '/'
        }
        return Promise.reject(error)
    }
)

export default api