const STORAGE_KEY = 'cart:priceChangedPending'

const readSet = () => {
  try {
    const raw = sessionStorage.getItem(STORAGE_KEY)
    return new Set(raw ? JSON.parse(raw) : [])
  } catch (e) {
    return new Set()
  }
}

const writeSet = (set) => {
  try {
    sessionStorage.setItem(STORAGE_KEY, JSON.stringify([...set]))
  } catch (e) {}
}

export const hasPendingPriceChange = (orderItemId) => {
  if (!orderItemId) return false
  return readSet().has(orderItemId)
}

export const addPendingPriceChange = (orderItemId) => {
  if (!orderItemId) return
  const set = readSet()
  if (!set.has(orderItemId)) {
    set.add(orderItemId)
    writeSet(set)
  }
}

export const removePendingPriceChange = (orderItemId) => {
  if (!orderItemId) return
  const set = readSet()
  if (set.delete(orderItemId)) {
    writeSet(set)
  }
}
