<script>
import Swal from "sweetalert2";

export const handleEconomicError = (error) => {
  if (error.response) {
    // Check if the response has the economic_error meta field
    if (error.response.data.meta && error.response.data.meta.economic_errors) {
      // Turn the economic_errors object into a string and display it

      Swal.fire({
        title: 'Fejl fra e-conomic',
        text: error.response.data.data.message,
        icon: 'error',
        confirmButtonText: 'Læs mere',
        cancelButtonText: 'OK',
        showCancelButton: true,
      })
      .then((result) => {
        if (result.isConfirmed) {
          Swal.fire({
            title: 'Fejl fra e-conomic',
            html: '<pre style="text-align: left; max-height: 40vh; overflow-y: auto;">' + JSON.stringify(error.response.data.meta.economic_errors, null, 2) + '</pre>',
            icon: 'error',
            confirmButtonText: 'Kopier til udklipsholder',
            cancelButtonText: 'Luk',
            showCancelButton: true,
            width: '50rem',
          })
          .then((result) => {
            if (result.isConfirmed) {
              navigator.clipboard.writeText(JSON.stringify(error.response.data.meta.economic_errors, null, 2));
            }
          });
        }
      });
      return;
    }
    // The request was made and the server responded with a status code
    // that falls out of the range of 2xx
    if (error.response.data.data.message) {
      Swal.fire({
        title: 'Fejl',
        text: error.response.data.data.message,
        icon: 'error',
        confirmButtonText: 'OK'
      });
    } else {
      Swal.fire({
        title: 'Fejl',
        text: error.response.data.message,
        icon: 'error',
        confirmButtonText: 'OK'
      });
    }
  } else if (error.request) {
    // The request was made but no response was received
    Swal.fire({
      title: 'Fejl',
      text: 'Ingen respons modtaget',
      icon: 'error',
      confirmButtonText: 'OK'
    });
  } else {
    // Something happened in setting up the request that triggered an Error
    Swal.fire({
      title: 'Fejl',
      text: 'Der skete en fejl',
      icon: 'error',
      confirmButtonText: 'OK'
    });
  }
  // Log the error to the console
  console.log('Caught error:', error);
};
</script>