<script>
import { ref } from "vue";
import { authenticatedRequest } from "@/components/session/authenticatedRequest.vue";
import { parseError } from "@/components/request/HandleGlobalError.vue";
import Swal from "sweetalert2";
/**
 * The Cron object
 * This object is used to fetch the cron jobs, and run them
 * @type {{runCron: (function(*=): Promise<void>)}}
 */
export const Cron = {
  /**
   * The run cron function
   * @param endpoint The (optional) endpoint to run the cron job on
   * @returns {Promise<void>}
   */
  runCron: async (endpoint = '') => {
    return await authenticatedRequest('/superuser/cron', "POST", {
      job: endpoint === '' ? null : endpoint
    })
        .then(
            (response) => {
              // Success
              Swal.fire({
                title: 'Success',
                text: 'The cron job has been run',
                icon: 'success',
                confirmButtonText: 'OK'
              });
            }
        )
        .catch(
            (error) => {
              parseError(error, 'universalRunCron');
            }
        );
  },
  /**
   * The get cron status function
   * @param endpoint
   * @returns {Promise<void>}
   */
  getCronStatus: async (endpoint) => {
    return await authenticatedRequest(endpoint, "GET", {})
        .then(
            (response) => {
              // Success
              Swal.fire({
                title: 'Success',
                text: 'The cron job has been run',
                icon: 'success',
                confirmButtonText: 'OK'
              });
            }
        )
        .catch(
            (error) => {
              parseError(error, 'universalRunCron');
            }
        );
  },
  /**
   * Cron jobs
   */
  cronJobs: ref([
    {
      name: 'All cron jobs',
      description: 'Run all cron jobs',
      icon: 'fas fa-sync-alt',
      endpoint: ''
    },
    {
      name: 'Syncronize logs',
      description: 'Syncronize the logs',
      icon: 'fas fa-sync-alt',
      endpoint: 'SyncLogs'
    },
    {
      name: 'Syncronize bookings',
      description: 'Syncronize the bookings',
      icon: 'fas fa-sync-alt',
      endpoint: 'SyncBookings'
    },
    {
      name: 'Check unfulfilled bookings',
      description: 'Check if there are any unfulfilled bookings',
      icon: 'fas fa-sync-alt',
      endpoint: 'CheckUnfulfilledBookings'
    },
    {
      name: 'Clear all users economic discount from cache',
      description: 'Clear all users economic discount from cache',
      icon: 'fas fa-sync-alt',
      endpoint: 'ClearEconomicDiscountCache'
    }
  ])
};

</script>