import axios from 'axios';

export const api = axios.create({
  baseURL: import.meta.env.VITE_API_URL || 'http://localhost:3000/api',
  timeout: 15000,
});

const token = window.localStorage.getItem('incusBackupApiToken') || import.meta.env.VITE_API_TOKEN;
if (token) {
  api.defaults.headers.common.Authorization = `Bearer ${token}`;
}

export function setApiToken(tokenValue) {
  const token = String(tokenValue || '');
  if (token) {
    window.localStorage.setItem('incusBackupApiToken', token);
    api.defaults.headers.common.Authorization = `Bearer ${token}`;
    return;
  }
  window.localStorage.removeItem('incusBackupApiToken');
  delete api.defaults.headers.common.Authorization;
}

export function errorMessage(error) {
  return error.response?.data?.error || error.message || 'Request failed.';
}
