export const scheduleUsesServicePackageDiscount = (item) => {
  const count = Number(
    item?.schedules?.[0]?.service_package_items_count
    ?? item?.service_package_items_count
    ?? item?.cart_items_count
    ?? item?.cartItemsCount
    ?? item?.cart?.items_count
    ?? 0
  )
  return count >= 3
}

export const getSchedulePlatformFeeRate = (schedule, paymentType, platformFees) => {
  const fees = platformFees?.value ?? platformFees ?? {}

  if (scheduleUsesServicePackageDiscount(schedule)) {
    const key = paymentType === 'credit_card'
      ? 'service_package_min_3_schedules_credit_card'
      : 'service_package_min_3_schedules_pix'

    if (fees[key] !== null && fees[key] !== undefined) {
      return fees[key]
    }
  }

  return fees[paymentType]
}

export const getSchedulePaymentType = (schedule, fallback = 'pix') => {
  const raw = schedule?.payment_method
    ?? schedule?.paymentMethod
    ?? schedule?.payment?.payment_method
    ?? schedule?.payment?.method
    ?? fallback

  const value = String(raw ?? fallback).toLowerCase()

  if (value.includes('credit') || value.includes('card')) return 'credit_card'
  if (value.includes('pix')) return 'pix'

  return fallback
}

export const getScheduleTotalWithPlatformFee = (schedule, paymentType, platformFees) => {
  const base = Number(schedule?.total_amount) || 0
  const feeRate = getSchedulePlatformFeeRate(schedule, paymentType, platformFees)

  return parseFloat((base * (1 + (feeRate ?? 0))).toFixed(2))
}
