<script>
import { ref } from 'vue'
import axios from 'axios'
import {API_URL} from "@/main.js";

export const getProducts = (departmentId = null) => {
  const token = localStorage.getItem('token');
  if (!token) {
    return null;
  }
  return axios.get(API_URL + '/products' + (departmentId ? '?department_id=' + departmentId : ''), {
    headers: {
      Authorization: `Bearer ${token}`
    }
  });
};

export const getProductCategory = (category, departmentId = null) => {
  const token = localStorage.getItem('token');
  if (!token) {
    return null;
  }
  // If the category is null, return all products
  if (!category || category === 'null') {
    return axios.get(API_URL + '/products' + (departmentId ? '?department_id=' + departmentId : ''), {
      headers: {
        Authorization: `Bearer ${token}`
      }
    });
  }
  return axios.get(API_URL + '/products?category=' + category + (departmentId ? '&department_id=' + departmentId : ''), {
    headers: {
      Authorization: `Bearer ${token}`
    }
  });
};

export const createProduct = (name, description, price, category, piktogram, economicProductId) => {
  const token = localStorage.getItem('token');
  if (!token) {
    return null;
  }
  return axios.post(API_URL + '/products', {
    name,
    description,
    price,
    category,
    piktogram,
    economicProductId
  }, {
    headers: {
      Authorization: `Bearer ${token}`
    }
  });
};

export const editProduct = (id, name, description, price, category, piktogram, economicProductId, applyCategoryDiscount) => {
  const token = localStorage.getItem('token');
  if (!token) {
    return null;
  }
  return axios.put(API_URL + '/products', {
    id,
    name,
    description,
    price,
    category,
    piktogram,
    economicProductId,
    applyCategoryDiscount
  }, {
    headers: {
      Authorization: `Bearer ${token}`
    }
  });
};
</script>