import axios from 'axios';
import store from './store';
import router from './router';

// Einheitliche Basis-URL:
// - immer relativ zur aktuellen Origin
// - kein absoluter http/https-Host → verhindert Mixed-Content-Probleme
axios.defaults.baseURL = '/api';
console.log('Axios baseURL:', axios.defaults.baseURL);

axios.interceptors.request.use(
  config => {
    const token = store.state.token;
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

axios.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    if (error.response && error.response.status === 401) {
      store.dispatch('logout').then(() => {
        if (router.currentRoute.value.path !== '/auth/login') {
          router.replace('/auth/login');
        }
      });
    }
    return Promise.reject(error);
  }
);

export default axios;
