<script>
import { ref } from 'vue'


/** Define the errors ref */
export const errors = ref([]);

/** Define the getError function */
export const getError = (name = null) => {
  console.log(errors.value);
  if (name) {
    const result = errors.value.find(error => error.name === name);
    console.log(result);
    return result ? result.error : null;
  }
  return errors.value;
};

/** Define the hasError function */
export const hasError = (name = null) => {
  if (name) {
    return errors.value.some(error => error.name === name);
  }
  return errors.value.length > 0;
};

/** Define the removeError function */
export const removeError = (name = null) => {
  if (name) {
    errors.value = errors.value.filter(error => error.name !== name);
    return;
  }
  // If no name is provided, clear all errors
  errors.value = [];
};

/** Define the clearErrors function */
export const clearErrors = () => {
  // Clear all errors if no specific error is provided
  errors.value = [];
};

/** Define the addError function */
export const addError = (error, name = null) => {
  if (name) {
    errors.value.push({name, error});
    return;
  }
  errors.value.push(error);
};

/** Define the parseError function */

export const parseError = (error, name = null) => {
  if (error.response) {
    // The request was made and the server responded with a status code
    // that falls out of the range of 2xx
    /** If the response has the custom error message */
    if (error.response.data.data.message) {
      addError(error.response.data.data.message, name);
    } else {
      /** Fall back to the default error message */
      addError(error.response.data.message, name);
    }
  } else if (error.request) {
    // The request was made but no response was received
    addError('No response was received', name);
  } else {
    // Something happened in setting up the request that triggered an Error
    addError(error, name);
  }
  // Log the error to the console
  console.log('Caught error:', error);
};
</script>