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`);

export const getCart = () => axios.get(`${API_URL}/cart/`);
export const addToCart = (data) => axios.post(`${API_URL}/cart/`, data);
export const updateCartItem = (id, data) =>
  axios.patch(`${API_URL}/cart/${id}`, data);
export const removeFromCart = (id) => axios.delete(`${API_URL}/cart/${id}`);
export const createOrder = (data) => axios.post(`${API_URL}/orders/`, data);
export const getUserOrders = () => axios.get(`${API_URL}/orders`);
export const getOrder = (id) => axios.get(`${API_URL}/orders/${id}`);

export const updateProfile = (data) => axios.patch(`${API_URL}/profile`, data);
export const getUserInfo = () => axios.get(`${API_URL}/profile`);

export const uploadItemAvatar = (id, file) => {
  const formData = new FormData();
  formData.append("avatar", file);
  return axios.patch(`${API_URL}/admin/items/${id}/avatar`, formData, {
    headers: { "Content-Type": "multipart/form-data" },
  });
};

export const getAllOrders = () => axios.get(`${API_URL}/admin/orders`);
export const updateOrderStatus = (id, data) =>
  axios.patch(`${API_URL}/admin/orders/${id}`, data);
export const registerAdmin = (data) =>
  axios.post(`${API_URL}/admin/register`, data);

export const stockIn = (data) => axios.post(`${API_URL}/admin/stock/in`, data);
export const stockOut = (data) =>
  axios.post(`${API_URL}/admin/stock/out`, data);
export const getStockMovements = () =>
  axios.get(`${API_URL}/admin/stock/movements`);
export const getTopItems = () => axios.get(`${API_URL}/admin/items/top`);
export const getAdminOrder = (id) => axios.get(`${API_URL}/admin/orders/${id}`);
