/**
 * Immediate delivery for marketplaces without a write throttle (eBay, Shopify, Shopware): the
 * routes that queue a change call this right away, so the user sees the result of the push in
 * the same request instead of waiting for the timer. Amazon keeps the batched outbox (5 req/s,
 * feeds). The change rows stay as audit trail either way; a failed immediate flush simply leaves
 * the change queued for the timer.
 */
import { flushOutbox, type FlushSummary } from './outbox'
import { deliversImmediately } from './adapters'
import type { IdempiereFetch } from './listingStore'

export const flushNowIfImmediate = async (f: IdempiereFetch, orderSource: any): Promise<FlushSummary | null> => {
  if (!orderSource || !deliversImmediately(orderSource)) return null
  try {
    return await flushOutbox({ orderSourceId: Number(orderSource.id), trigger: 'manual', fetch: f, maxRunMs: 25_000, ignoreDebounce: true })
  } catch (e: any) {
    console.warn('[listing-outbox] immediate flush failed, change stays queued:', e?.message || e)
    return null
  }
}
