import axios from 'axios';

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

// Request: attach JWT
client.interceptors.request.use((config) => {
  const token = localStorage.getItem('t');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

// Response: handle 401 + extract data
client.interceptors.response.use(
  (res) => res.data,
  (err) => {
    if (err.response?.status === 401) {
      localStorage.removeItem('t');
      window.location.href = '/app/login';
    }
    const detail = err.response?.data?.detail || err.response?.data?.message || err.message || 'Erro';
    return Promise.reject(new Error(detail));
  }
);

export default client;
