<script>
import { ref } from 'vue';
import { authenticatedRequest } from "@/components/session/authenticatedRequest.vue";
import Swal from "sweetalert2";
// Define the department id
export const departmentId = ref(0);

// Define the department object
export const department = {
  id: ref(''),
  name: ref(''),
  description: ref(''),
  created_at: ref(''),
  updated_at: ref(''),
  prices: ref([])
}

const isDepartmentPricesLoaded = ref(false);

// Set the department id
export const setDepartment = (id) => {
  departmentId.value = id;
  // Load the department data
  getDepartmentData();
}

// Get the department data
export const getDepartmentData = async () => {
  return await authenticatedRequest(`/superuser/department?department_id=${departmentId.value}`, "GET")
      .then((response) => {
        department.id.value = response.data.data.id;
        department.name.value = response.data.data.name;
        department.description.value = response.data.data.description;
        department.created_at.value = response.data.data.created_at;
        department.updated_at.value = response.data.data.updated_at;
      })
}

export const getDepartmentPrices = async () => {
  return await authenticatedRequest(`/superuser/department/prices?department_id=${departmentId.value}`, "GET")
      .then((response) => {
        department.prices.value = response.data.data;
      })
      .catch((error) => {
        department.prices.value = [];
        isDepartmentPricesLoaded.value = false;
      });
}

export const getDepartmentPrice = (product) => {
  // If the department prices aren't loaded, load them
  if (!isDepartmentPricesLoaded.value) {
    isDepartmentPricesLoaded.value = true;
    getDepartmentPrices();
  }
  if (isDepartmentPricesLoaded.value) {
    const price = department.prices.value.find((price) => price.product_id === product.id);
    return price ? price.price : product.price;
  }
  return product.price;
}

export const editDepartmentPrice = (product) => {
  Swal.fire({
    title: product.name + ' ( product: ' + product.id + ' )',
    input: 'number',
    inputValue: getDepartmentPrice(product),
    inputLabel: 'Price',
    inputAttributes: {
      autocapitalize: 'off'
    },
    showCancelButton: true,
    confirmButtonText: 'Save',
    showLoaderOnConfirm: true,
    preConfirm: (price) => {
      return authenticatedRequest(`/superuser/department/prices`, "POST", {
        department_id: departmentId.value,
        product_id: product.id,
        price: price
      })
          .then((response) => {
            console.log(response);
            getDepartmentPrices();
          })
          .catch((error) => {
            console.log(error);
          });
    },
    allowOutsideClick: () => !Swal.isLoading()
  });
}
</script>