import { getAffiliateDashConfig } from '../../platforms/affiliate-dash/config.js'
import type { JsonObject } from '../../../types/json.js'
import { getAffiliateDashWallet } from '../../platforms/affiliate-dash/order-service.js'
import { listAffiliateDashProducts } from '../../platforms/affiliate-dash/product-service.js'
import {
  getAffiliateDashSourceConfig,
  hasAffiliateDashConfig,
  normalizeAffiliateDashSourceConfig,
  saveAffiliateDashSourceConfig,
} from '../../platforms/affiliate-dash/source-config-service.js'

export function getAdminAffiliateDashConfig() {
  const source = getAdminEditableAffiliateDashConfig()
  const effective = getAffiliateDashConfig()

  return {
    source,
    effective: mapEffectiveAffiliateDashConfig(effective),
  }
}

export async function updateAdminAffiliateDashConfig(payload: JsonObject = {}) {
  const saved = await saveAffiliateDashSourceConfig(payload)
  const effective = getAffiliateDashConfig()

  return {
    source: saved,
    effective: mapEffectiveAffiliateDashConfig(effective),
  }
}

/** 按 91 商品编码（productNo）测试 sku 映射命中。 */
export function matchAdminAffiliateDashSku(payload: JsonObject = {}) {
  const productNo = String(payload.productNo || payload.product_no || '').trim()
  const source = getAdminEditableAffiliateDashConfig()
  const sku = productNo ? String(source.skuMapping[productNo] || '').trim() : ''

  return {
    productNo,
    sku,
    matched: Boolean(productNo && sku),
  }
}

export async function listAdminAffiliateDashProducts(payload: JsonObject = {}) {
  return listAffiliateDashProducts({
    page: Number(payload.page || 1) || 1,
    size: Math.min(200, Math.max(1, Number(payload.size || 50) || 50)),
  })
}

export async function getAdminAffiliateDashWallet() {
  return getAffiliateDashWallet()
}

function getAdminEditableAffiliateDashConfig() {
  if (hasAffiliateDashConfig()) {
    return getAffiliateDashSourceConfig()
  }

  return normalizeAffiliateDashSourceConfig(getAffiliateDashConfig())
}

function mapEffectiveAffiliateDashConfig(config: ReturnType<typeof getAffiliateDashConfig>) {
  return {
    enabled: config.enabled !== false,
    baseUrl: config.baseUrl,
    timeoutMs: config.timeoutMs,
    notifyUrl: config.notifyUrl,
    timestampToleranceSeconds: config.timestampToleranceSeconds,
    preferredMatchEnabled: config.preferredMatchEnabled !== false,
    hasAppKey: Boolean(config.appKey),
    hasAppSecret: Boolean(config.appSecret),
    hasCallbackSecret: Boolean(config.callbackSecret),
    skuMappingCount: Object.keys(config.skuMapping).length,
  }
}
