import { normalizeAgisoMessageTemplate } from '../../platforms/agiso/xianyu/message-service.js'
import { maskSecret } from './mappers.js'

type JsonObject = Record<string, any>

export function mapAdminAgisoMessagingDefaults(defaults: JsonObject = {}) {
  return {
    messageTemplate: normalizeAgisoMessageTemplate(String(defaults.messageTemplate || '').trim()),
    autoDeliveryMessageTemplate: normalizeAgisoMessageTemplate(
      String(defaults.autoDeliveryMessageTemplate || '').trim(),
    ),
  }
}

export function mapAdminAgisoShopConfigItem(shopId: unknown, config: JsonObject = {}) {
  return {
    shopId,
    shopName: String(config.shopName || '').trim(),
    accessToken: String(config.accessToken || '').trim(),
    accessTokenMasked: maskSecret(config.accessToken),
    enabled: typeof config.enabled === 'boolean' ? config.enabled : null,
    messageTemplate: normalizeAgisoMessageTemplate(String(config.messageTemplate || '').trim()),
    autoDeliveryMessageTemplate: normalizeAgisoMessageTemplate(
      String(config.autoDeliveryMessageTemplate || '').trim(),
    ),
    appSecretConfigured: Boolean(String(config.appSecret || '').trim()),
    apiVersion: String(config.apiVersion || '').trim(),
    sendMessageEndpoint: String(config.sendMessageEndpoint || '').trim(),
  }
}

export function applyOptionalStringField(target: JsonObject, key: string, source: JsonObject) {
  if (!source || typeof source[key] !== 'string') {
    return
  }

  const value = String(source[key] || '').trim()
  if (value) {
    target[key] = normalizeAgisoMessageTemplate(value)
    return
  }

  delete target[key]
}

export function mapAdminFulfillmentBindingConfigItem(item: JsonObject) {
  const match = item?.match || {}
  return {
    provider: String(item?.provider || '').trim(),
    platform: String(item?.platform || '').trim(),
    shopId: String(item?.shopId || '').trim(),
    shopName: String(item?.shopName || '').trim(),
    skuCode: String(item?.skuCode || '').trim(),
    skuName: String(item?.skuName || '').trim(),
    profileKey: String(item?.profileKey || '').trim(),
    enabled: item?.enabled !== false,
    priority: Number(item?.priority || 100),
    config: item?.config || {},
    match: {
      externalSkuCode: String(match.externalSkuCode || '').trim(),
      externalItemId: String(match.externalItemId || '').trim(),
      externalSkuName: String(match.externalSkuName || '').trim(),
      config: match.config || {},
    },
  }
}

export function matchesObservedProduct(binding: JsonObject, observed: JsonObject) {
  const provider = String(binding?.provider || '').trim()
  const platform = String(binding?.platform || '').trim()
  const shopId = String(binding?.shopId || '').trim()
  const match = binding?.match || {}
  const externalSkuCode = String(match.externalSkuCode || '').trim()
  const externalItemId = String(match.externalItemId || '').trim()
  const externalSkuName = String(match.externalSkuName || '').trim()

  if (provider && provider !== String(observed?.provider || '').trim()) {
    return false
  }

  if (platform && platform !== String(observed?.platform || '').trim()) {
    return false
  }

  if (shopId && shopId !== String(observed?.shopId || '').trim()) {
    return false
  }

  return (
    (externalSkuCode && externalSkuCode === String(observed?.externalSkuCode || '').trim())
    || (externalItemId && externalItemId === String(observed?.externalItemId || '').trim())
    || (externalSkuName && externalSkuName === String(observed?.externalSkuName || '').trim())
  )
}

export function findMatchingObservedBinding(bindings: JsonObject[], observed: JsonObject) {
  return (Array.isArray(bindings) ? bindings : []).find((binding) => matchesObservedProduct(binding, observed)) || null
}

export function mapAdminObservedProductItem(item: JsonObject, bindings: JsonObject[] = []) {
  const matchedBinding = findMatchingObservedBinding(bindings, item)

  return {
    provider: String(item?.provider || '').trim(),
    platform: String(item?.platform || '').trim(),
    shopId: String(item?.shopId || '').trim(),
    shopName: String(item?.shopName || '').trim(),
    externalItemId: String(item?.externalItemId || '').trim(),
    externalSkuCode: String(item?.externalSkuCode || '').trim(),
    externalSkuName: String(item?.externalSkuName || '').trim(),
    latestSeenAt: item?.latestSeenAt || null,
    orderItemCount: Number(item?.orderItemCount || 0),
    configured: Boolean(matchedBinding),
    matchedBinding: matchedBinding
      ? {
          skuCode: String(matchedBinding.skuCode || '').trim(),
          skuName: String(matchedBinding.skuName || '').trim(),
          profileKey: String(matchedBinding.profileKey || '').trim(),
        }
      : null,
  }
}
