<script>

import {ref, watch} from "vue";
import { authenticatedRequest } from "@/components/session/authenticatedRequest.vue";
// Get the user from the route
export const userId = ref(0);

export const setUser = (id) => {
  userId.value = id;
  // Load the user data
  getUserData();
}

export const onUserChange = (callback) => {
  watch(userId, (newValue) => {
    if (newValue) {
      callback(newValue);
    }
  });
}




export const getUserCustomerNumber = () => {
  return user.customer_number.value;
}

// Get the user data
export const getUserData = async () => {
  return await authenticatedRequest(`/superuser/user?user_id=${userId.value}`, "GET")
      .then((response) => {
        user.id.value = response.data.data.id;
        user.customer_number.value = response.data.data.customer_number;
        user.group_id.value = response.data.data.group_id;
        user.created_at.value = response.data.data.created_at;
        user.updated_at.value = response.data.data.updated_at;
        if (response.data.data.economic_customer.name) {
          user.economicData.customerNumber.value = response.data.data.economic_customer.customerNumber;
          user.economicData.name.value = response.data.data.economic_customer.name;
          user.economicData.address.value = response.data.data.economic_customer.address;
          user.economicData.zip.value = response.data.data.economic_customer.zip;
          user.economicData.city.value = response.data.data.economic_customer.city;
          user.economicData.mobilePhone.value = response.data.data.economic_customer.mobilePhone;
          user.economicData.email.value = response.data.data.economic_customer.email;
          user.economicData.cvr.value = response.data.data.economic_customer.corporateIdentificationNumber;
          user.economicData.currency.value = response.data.data.economic_customer.currency;
          user.economicData.country.value = response.data.data.economic_customer.country;
          user.economicData.barred.value = response.data.data.economic_customer.barred ?? false;
        }
        user.permissions.value = response.data.data.permissions;
        user.attributes.value = response.data.data.attributes;
        user.discounts.value = response.data.data.discounts;
        user.orders_not_invoiced.value = response.data.data.orders_not_invoiced || null;
        user.keys.value = response.data.data.keys;
        user.wash_subscription_transactions.value = response.data.data.wash_subscription_transactions || null;
        console.log(user.discounts.value);
      })
      .catch((error) => {
        console.error(error);
      });
};

/** Get user product discount */
export const getUserProductDiscount = (product, allowCategory = 1, onlyCategory = 0, allowGlobal = 0) => {
  // Get the product id
  const productId = product.id;
  // Get the product category
  const category = product.category;
  // Find the discount for the product
  let discount = null;
  let categoryDiscount = null;
  let globalDiscount = getUserGlobalDiscount();
  try {
    discount = user.discounts.value.find(discount => discount.product_or_category_id == productId && discount.is_category == 0) || null;
  } catch (e) {}
  // If the discount is not found, return 0
  if (allowCategory === 1) {
    // Check if the category has a discount
    try {
      categoryDiscount = user.discounts.value.find(discount => discount.is_category == 1 && discount.product_or_category_id == category) || null;
    } catch (e) {}
    // If the onlyCategory is 1, return the category discount
    // Likewise, if the discount is not found, return the category discount or 0 (if not found)
    if (!discount) {
      if (onlyCategory === 1) {
        return categoryDiscount ? categoryDiscount.percentage : 0;
      }
    }
    if (onlyCategory === 1) {
      return categoryDiscount ? categoryDiscount.percentage : 0;
    }
    if (!categoryDiscount) {
      return discount ? discount.percentage : 0;
    }
    // If the category discount is higher than the product discount, return the category discount
    if (parseInt(categoryDiscount.percentage) > parseInt(discount.percentage)) {
      return categoryDiscount.percentage;
    }
    return discount.percentage;
  } else {
    return discount ? discount.percentage : 0;
  }
};

export const getUserCategoryDiscount = (category) => {
  // Find the category discount
  let categoryDiscount = null;
  try {
    categoryDiscount = parseInt(user.discounts.value.find(
        (discount) =>
            parseInt(discount.product_or_category_id) === category && discount.is_category
    ).percentage) || null;
  } catch (e) {}
  return categoryDiscount ? categoryDiscount : 0;
};

export const getUserGlobalDiscount = () => {
  // Find the global discount
  let globalDiscount = null;
  try {
    globalDiscount = parseInt(user.discounts.value.find(
        (discount) =>
            discount.id === 999999
    ).percentage) || null;
  } catch (e) {}
  return globalDiscount ? globalDiscount : 0;
};

export const getUserProductOnlyDiscount = (product) => {
  // Get the product id
  const productId = product.id;
  // Find the discount for the product
  let discount = null;
  try {
    discount = user.discounts.value.find(discount => discount.product_or_category_id == productId && !discount.is_category) || null;
  } catch (e) {}
  // If the discount is not found, return 0
  return discount ? discount.percentage : 0;
};

export const isProductAllowedToApplyCategoryDiscounts = (product) => {
  // Check if the product is allowed to apply category discounts
  return parseInt(product.apply_category_discount) === 1;
};

export const getProductCategory = (product) => {
  // Get the product category
  return product.category;
};

export const getProductBestApplicableDiscount = (product) => {
  // Get the product id
  const productId = product.id;
  // Get the product category
  const category = getProductCategory(product);
  // Find the discount for the product
  let productDiscount = getUserProductOnlyDiscount(product);
  let categoryDiscount = getUserCategoryDiscount(category);
  let globalDiscount = getUserGlobalDiscount();
  // Check if the product is allowed to apply category discounts
  if (!isProductAllowedToApplyCategoryDiscounts(product)) {
    categoryDiscount = 0;
    globalDiscount = 0;
  }
  return Math.max(productDiscount, categoryDiscount, globalDiscount);
}

export const user = {
  id: ref(''),
  customer_number: ref(''),
  group_id: ref(''),
  created_at: ref(''),
  updated_at: ref(''),
  economicData: {
    customerNumber: ref(null),
    name: ref(null),
    address: ref(null),
    zip: ref(null),
    city: ref(null),
    mobilePhone: ref(null),
    email: ref(null),
    cvr: ref(null),
    currency: ref(null),
    country: ref(null),
    barred: ref(null),
  },
  permissions: ref(null),
  attributes: ref(null),
  discounts: ref(null),
  orders_not_invoiced: ref(null),
  keys: ref({
    open_invoice_draft: ref(null),
  }),
  wash_subscription_transactions: ref(null),
  functions: {
    getUserData: getUserData,
    getUserProductDiscount: getUserProductDiscount,
    getUserCategoryDiscount: getUserCategoryDiscount,
    getUserGlobalDiscount: getUserGlobalDiscount,
    getUserProductOnlyDiscount: getUserProductOnlyDiscount,
    isProductAllowedToApplyCategoryDiscounts: isProductAllowedToApplyCategoryDiscounts,
    getProductCategory: getProductCategory,
    getProductBestApplicableDiscount: getProductBestApplicableDiscount,
  },
};
</script>
