import axios from 'axios';
import { useAuth } from '../stores/useAuth';

const http = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
});

http.interceptors.request.use((config: any) => {
  const auth = useAuth();
  if (auth.token.value) {
    config.headers = {
      ...config.headers,
      Authorization: `Bearer ${auth.token.value}`
    };
  }
  return config;
});

http.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    const status = error.response?.status;
    if (status === 401 || status === 403) {
      const auth = useAuth();
      auth.logout();
    }
    return Promise.reject(error);
  }
);

export default http;
