<script>
import {ref} from 'vue'
import axios from 'axios'
import {API_URL} from "@/main.js";
import { parseError } from "@/components/request/HandleGlobalError.vue";
import {SessionUser} from "@/components/session/token/SessionUser.vue";
import {authenticatedRequest} from "@/components/session/authenticatedRequest.vue";

export const searchCustomerResults = ref([]);
export const searchCustomerPagination = ref([]);
export const searchCustomerMeta = ref([]);
export const isSearching = ref(false);

export const searchCustomer = (search = null, filter = false) => {
  const token = localStorage.getItem('token');
  if (!token) {
    return null;
  }
  if (!search) {
    // Reset the search results
    searchCustomerResults.value = [];
    return null;
  }
  // If the filter is set to false, we want to predict the filter
  if (!filter) {
  }
  // Reset the search results
  searchCustomerResults.value = [];
  isSearching.value = true;
  // Search for the customer
  return authenticatedRequest(
      '/customers?search=' + search,
  )
      .then((response) => {
        searchCustomerResults.value = response.data.data;
        searchCustomerPagination.value = response.data.meta.pagination;
        searchCustomerMeta.value = response.data.meta;
        isSearching.value = false;
        return searchCustomerResults.value
      })
      .catch((error) => {
        isSearching.value = false;
        parseError(error);
      });
};
</script>