import { ref } from 'vue';

import { getPriceAdjustConfig } from '#/views/system/system-config/api';

import type { QuickDiscountOption } from '#/utils/pricePercentAdjust';
import { applyRatioToDrug, applyRatioToDrugs, formatPriceDiscountLabel, normalizeQuickOptions } from '#/utils/pricePercentAdjust';

export type PriceAdjustConfig = {
  order_price_adjust_scope: 'both' | 'sale_only';
  order_discount_quick_options: QuickDiscountOption[];
  enable_order_price_percent_adjust: boolean;
  store_id?: number;
};

const defaultConfig: PriceAdjustConfig = {
  order_price_adjust_scope: 'sale_only',
  order_discount_quick_options: normalizeQuickOptions([]),
  enable_order_price_percent_adjust: false,
};

export function useOrderPriceAdjust() {
  const config = ref<PriceAdjustConfig>({ ...defaultConfig });
  const loading = ref(false);

  async function loadByStoreId(storeId?: number) {
    if (!storeId) {
      config.value = { ...defaultConfig };
      return config.value;
    }
    loading.value = true;
    try {
      const res = await getPriceAdjustConfig(storeId);
      config.value = {
        order_price_adjust_scope: res?.order_price_adjust_scope === 'both' ? 'both' : 'sale_only',
        order_discount_quick_options: normalizeQuickOptions(res?.order_discount_quick_options),
        enable_order_price_percent_adjust: !!res?.enable_order_price_percent_adjust,
        store_id: storeId,
      };
      return config.value;
    } finally {
      loading.value = false;
    }
  }

  function setFromOrderStore(store?: { enable_order_price_percent_adjust?: number | boolean }) {
    config.value = {
      ...config.value,
      enable_order_price_percent_adjust: Number(store?.enable_order_price_percent_adjust) === 1,
    };
  }

  async function loadGlobalOptions() {
    const res = await getPriceAdjustConfig();
    config.value = {
      ...config.value,
      order_price_adjust_scope: res?.order_price_adjust_scope === 'both' ? 'both' : 'sale_only',
      order_discount_quick_options: normalizeQuickOptions(res?.order_discount_quick_options),
    };
  }

  return {
    config,
    loading,
    loadByStoreId,
    loadGlobalOptions,
    setFromOrderStore,
    applyRatioToDrug,
    applyRatioToDrugs,
    formatPriceDiscountLabel,
  };
}
