import { normalizeCloudtentaclesMatchName } from '../../order/cloudtentacles-match-utils.js'
import { getKuaishouFeifeiConfig } from './config.js'
import type { KuaishouFeifeiProductRule } from '../../../types/runtime-config.js'

export type KuaishouFeifeiProductMatch = {
  matchMode: 'kuaishou_feifei_name'
  productName: string
  normalizedProductName: string
  productCode: string
  skuName: string
}

export function resolveKuaishouFeifeiProductByName(
  productName: unknown,
  options: {
    rules?: KuaishouFeifeiProductRule[]
    enabled?: boolean
  } = {},
): KuaishouFeifeiProductMatch | null {
  const normalizedProductName = normalizeCloudtentaclesMatchName(productName)
  if (!normalizedProductName) {
    return null
  }

  const rules = listKuaishouFeifeiProductRules(options)
  const matched = rules.find(
    (rule) =>
      normalizeCloudtentaclesMatchName(rule.productName || rule.normalizedProductName) ===
      normalizedProductName,
  )

  if (!matched) {
    return null
  }

  const productCode = String(matched.productCode || '').trim()
  if (!productCode) {
    return null
  }

  return {
    matchMode: 'kuaishou_feifei_name',
    productName: String(matched.productName || productName || '').trim(),
    normalizedProductName,
    productCode,
    skuName: String(matched.skuName || matched.productName || productName || productCode).trim(),
  }
}

function listKuaishouFeifeiProductRules(options: {
  rules?: KuaishouFeifeiProductRule[]
  enabled?: boolean
}): KuaishouFeifeiProductRule[] {
  const config = options.rules ? null : getKuaishouFeifeiConfig()
  if (options.enabled === false || config?.enabled === false) {
    return []
  }

  const rules = options.rules || config?.productRules
  return (Array.isArray(rules) ? rules : [])
    .map((rule) => ({
      id: String(rule.id || '').trim(),
      productName: String(rule.productName || '').trim(),
      normalizedProductName: String(rule.normalizedProductName || '').trim(),
      productCode: String(rule.productCode || '').trim(),
      skuName: String(rule.skuName || '').trim(),
      enabled: rule.enabled !== false,
      notes: String(rule.notes || '').trim(),
    }))
    .filter((rule) => rule.enabled && rule.productName && rule.productCode)
}
