import axios from "axios";

const API_URL = "/api";

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

axios.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response && error.response.status === 401) {
      localStorage.removeItem("token");
      window.location.href = "/login";
    }
    return Promise.reject(error);
  },
);

// Базовые CRUD операции
export const getItem = (id) => axios.get(`${API_URL}/items/${id}`);
export const getAllItems = () => axios.get(`${API_URL}/items`);

export const addItem = (itemData) => axios.post(`${API_URL}/items`, itemData);

export const updateItem = (id, itemData) =>
  axios.patch(`${API_URL}/items/${id}`, itemData);

export const deleteItem = (id) => axios.delete(`${API_URL}/items/${id}`);

export const getAllCategories = () => axios.get(`${API_URL}/getCategories`)
