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

export const getAttributes = (customer_number) => {
  const token = localStorage.getItem('token');
  if (!token) {
    return null;
  }
  // If the customer number is empty, return null
  if (!customer_number) {
    return null;
  }
  return axios.get(API_URL + '/customer/attributes?customer_number=' + customer_number, {
    headers: {
      Authorization: `Bearer ${token}`
    }
  });
};

const isAttributesLoading = ref(false);

export const createAttribute = (customer_number, attribute) => {
  const token = localStorage.getItem('token');
  if (!token) {
    return null;
  }
  // If the loading state is true, return null
  if (isAttributesLoading.value) {
    return null;
  }
  // Set the loading state to true
  isAttributesLoading.value = true;
  return axios.post(API_URL + '/customer/attributes', {
    customer_number,
    attribute
  }, {
    headers: {
      Authorization: `Bearer ${token}`
    }
  }).then(
    () => {
      isAttributesLoading.value = false;
    }
  ).catch(
    () => {
      isAttributesLoading.value = false;
    }
  );
};

export const deleteAttribute = (customer_number, attribute) => {
  const token = localStorage.getItem('token');
  if (!token) {
    return null;
  }
  // If the loading state is true, return null
  if (isAttributesLoading.value) {
    return null;
  }
  // Set the loading state to true
  isAttributesLoading.value = true;
  return axios.delete(API_URL + '/customer/attributes?customer_number=' + customer_number + '&attribute=' + attribute, {
    headers: {
      Authorization: `Bearer ${token}`
    }
  }).then(
    () => {
      isAttributesLoading.value = false;
    }
  ).catch(
    () => {
      isAttributesLoading.value = false;
    }
  );
};
</script>