import type { ListingAdapter, MarketplaceKey } from './types'
import { amazonAdapter } from './amazon'
import { ebayAdapter } from './ebay'
import { shopifyAdapter } from './shopify'
import { shopwareAdapter } from './shopware'

// c_ordersource.Marketplace (AD_Reference 1000003): 1 shopware, 2 shopify, 4 amazon,
// 5 ebay, 6 plentyone, 7 csv, 8 jtl, 9 temu, 10 shopify-new, 12 manual.
export const marketplaceKeyOf = (orderSource: any): MarketplaceKey => {
  const ident = String(orderSource?.Marketplace?.identifier || orderSource?.marketplace?.identifier || '').toLowerCase()
  const id = Number(orderSource?.Marketplace?.id ?? orderSource?.marketplace ?? 0)
  if (ident === 'amazon' || id === 4) return 'amazon'
  if (ident === 'ebay' || id === 5) return 'ebay'
  if (ident === 'shopify-new' || id === 10) return 'shopify-new'
  if (ident === 'shopify' || id === 2) return 'shopify'
  if (ident === 'shopware' || ident === 'shopware6' || id === 1) return 'shopware'
  return 'unknown'
}

const adapters: Partial<Record<MarketplaceKey, ListingAdapter>> = {
  amazon: amazonAdapter,
  ebay: ebayAdapter,
  shopify: shopifyAdapter,
  'shopify-new': shopifyAdapter,
  shopware: shopwareAdapter
}

export const getListingAdapter = (orderSource: any): ListingAdapter | null => adapters[marketplaceKeyOf(orderSource)] || null

/** True when a working (non-stub) adapter exists for this order source. */
export const supportsListings = (orderSource: any): boolean => ['amazon', 'ebay', 'shopify', 'shopify-new', 'shopware'].includes(marketplaceKeyOf(orderSource))

/** Marketplaces without a per-second write throttle deliver a change right after it was queued. */
export const deliversImmediately = (orderSource: any): boolean => !!getListingAdapter(orderSource)?.immediate

/** Human label per marketplace key (UI + messages). */
export const marketplaceLabel = (key: MarketplaceKey | string): string =>
  ({ amazon: 'Amazon', ebay: 'eBay', shopify: 'Shopify', 'shopify-new': 'Shopify', shopware: 'Shopware 6' } as Record<string, string>)[String(key)] || String(key)
