import { getPaymentPlatformFees } from 'src/api/payment'
import { ref } from 'vue'

const platformFees = ref({
  pix: null,
  credit_card: null,
  service_package_min_3_schedules_credit_card: null,
  service_package_min_3_schedules_pix: null,
})

let loadingPromise = null

const normalizeFee = (value) => {
  if (value === null || value === undefined || value === '') return null

  const fee = Number(value)

  if (!Number.isFinite(fee)) return null

  return fee > 1 ? fee / 100 : fee
}

const firstDefined = (...values) => values.find((value) => value !== null && value !== undefined && value !== '')

const normalizePlatformFees = (fees) => {
  const normalized = {
    pix: normalizeFee(firstDefined(
      fees?.pix,
      fees?.PIX,
      fees?.pix_fee,
      fees?.pix_fee_rate,
      fees?.platform_pix_fee_rate,
    )),
    credit_card: normalizeFee(firstDefined(
      fees?.credit_card,
      fees?.creditCard,
      fees?.credit_card_fee,
      fees?.credit_card_fee_rate,
      fees?.platform_credit_card_fee_rate,
    )),
    service_package_min_3_schedules_credit_card: normalizeFee(firstDefined(
      fees?.service_package_min_3_schedules_credit_card,
      fees?.servicePackageMin3SchedulesCreditCard,
    )),
    service_package_min_3_schedules_pix: normalizeFee(firstDefined(
      fees?.service_package_min_3_schedules_pix,
      fees?.servicePackageMin3SchedulesPix,
    )),
  }

  if (normalized.pix === null || normalized.credit_card === null) {
    console.warn('Invalid payment platform fees payload', fees)
  }

  return normalized
}

export function usePaymentPlatformFees() {
  const loadPlatformFees = async () => {
    if (!loadingPromise) {
      loadingPromise = getPaymentPlatformFees()
        .then((fees) => {
          platformFees.value = normalizePlatformFees(fees)
        })
        .finally(() => {
          loadingPromise = null
        })
    }

    await loadingPromise
  }

  return {
    platformFees,
    loadPlatformFees,
  }
}
