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

export const authenticatedRequest = (url, method, data, catchCallable = null, thenCallable = null) => {
  const token = localStorage.getItem('token');
  if (!token) {
    throw new Error('No token was found, unable to make authenticated request');
  }
  // If the request is a GET request, add the data to the params instead
  return axios({
    method,
    url: API_URL + url,
    ...(method === 'GET' ? { params: data } : { data }),
    headers: {
      Authorization: `Bearer ${token}`
    }
  }).catch((error) => {
    console.error(error);
    if (catchCallable) {
      // Call the catch callable
      catchCallable(error);
    }
    throw error;
  }).then((response) => {
    if (thenCallable) {
      // Call the then callable
      thenCallable(response);
    }
    return response;
  });
};

export const unauthenticatedRequest = (url, method, data, catchCallable = null, thenCallable = null) => {
  return axios({
    method,
    url: API_URL + url,
    data
  }).catch((error) => {
    console.error(error);
    if (catchCallable) {
      // Call the catch callable
      catchCallable(error);
    }
    throw error;
  }).then((response) => {
    if (thenCallable) {
      // Call the then callable
      thenCallable(response);
    }
    return response;
  });
};

export const paginatedGetRequest = (url, currentPage, itemsPerPage) => {
  const token = localStorage.getItem('token');
  if (!token) {
    return null;
  }
  return axios.get(API_URL + url, {
    params: {
      page: currentPage,
      limit: itemsPerPage
    },
    headers: {
      Authorization: `Bearer ${token}`
    }
  });
};
</script>