import { getKuaishouFeifeiConfig } from '../../platforms/kuaishou-feifei/config.js'
import type { JsonObject } from '../../../types/json.js'
import {
  createKuaishouFeifeiOrder,
  listKuaishouFeifeiProducts,
  queryKuaishouFeifeiOrder,
  type KuaishouFeifeiProductListResult,
} from '../../platforms/kuaishou-feifei/order-service.js'
import { resolveKuaishouFeifeiProductByName } from '../../platforms/kuaishou-feifei/product-rule-service.js'
import {
  getKuaishouFeifeiConfigFilePath,
  getKuaishouFeifeiSourceConfig,
  hasKuaishouFeifeiConfigFile,
  normalizeKuaishouFeifeiSourceConfig,
  saveKuaishouFeifeiSourceConfig,
} from '../../platforms/kuaishou-feifei/source-config-service.js'
import { normalizeCloudtentaclesMatchName } from '../../order/cloudtentacles-match-utils.js'
import { createHttpError } from '../../../utils/http.js'

export function getAdminKuaishouFeifeiConfig() {
  const source = getAdminEditableKuaishouFeifeiConfig()
  const effective = getKuaishouFeifeiConfig()

  return {
    filePath: getKuaishouFeifeiConfigFilePath(),
    source,
    effective: mapEffectiveKuaishouFeifeiConfig(effective),
  }
}

export async function updateAdminKuaishouFeifeiConfig(payload: JsonObject = {}) {
  const saved = await saveKuaishouFeifeiSourceConfig(payload)
  const effective = getKuaishouFeifeiConfig()

  return {
    filePath: getKuaishouFeifeiConfigFilePath(),
    source: saved,
    effective: mapEffectiveKuaishouFeifeiConfig(effective),
  }
}

export function matchAdminKuaishouFeifeiProduct(payload: JsonObject = {}) {
  const productName = String(payload.productName || '').trim()
  const source = getAdminEditableKuaishouFeifeiConfig()
  const match = resolveKuaishouFeifeiProductByName(productName, {
    enabled: source.enabled,
    rules: source.productRules,
  })

  return {
    productName,
    normalizedProductName: normalizeCloudtentaclesMatchName(productName),
    matched: Boolean(match),
    match,
  }
}

export async function listAdminKuaishouFeifeiProducts(payload: JsonObject = {}) {
  return listKuaishouFeifeiProducts({
    page: Number(payload.page || 1) || 1,
    perPage: Number(payload.perPage || payload.per_page || 20) || 20,
    status: String(payload.status || 'on_sale').trim(),
    supplyProductName: String(
      payload.supplyProductName || payload.supply_product_name || '',
    ).trim(),
  })
}

export async function syncAdminKuaishouFeifeiProductRules(payload: JsonObject = {}) {
  const source = getAdminEditableKuaishouFeifeiConfig()
  const status = String(payload.status || 'on_sale').trim() || 'on_sale'
  const supplyProductName = String(
    payload.supplyProductName || payload.supply_product_name || '',
  ).trim()
  const products = await listAllKuaishouFeifeiProducts({
    status,
    supplyProductName,
  })
  const productRules = products
    .map((product) => {
      const productName = String(product.name || '').trim()
      const productCode = String(product.productCode || '').trim()
      if (!productName || !productCode) {
        return null
      }

      return {
        id: normalizeCloudtentaclesMatchName(productName) || productCode,
        enabled: product.status !== 'off_sale' && product.supplyStatus !== 'off_sale',
        productName,
        normalizedProductName: normalizeCloudtentaclesMatchName(productName),
        productCode,
        skuName: productName,
        notes: `feifei 商品目录同步：${product.channel || 'unknown'}`,
      }
    })
    .filter((rule): rule is NonNullable<typeof rule> => Boolean(rule))
  const saved = await saveKuaishouFeifeiSourceConfig({
    ...source,
    productRules,
  })
  const effective = getKuaishouFeifeiConfig()

  return {
    filePath: getKuaishouFeifeiConfigFilePath(),
    source: saved,
    effective: mapEffectiveKuaishouFeifeiConfig(effective),
    sync: {
      productCount: products.length,
      ruleCount: saved.productRules.length,
      status,
      supplyProductName,
    },
  }
}

export async function createAdminKuaishouFeifeiTestOrder(payload: JsonObject = {}) {
  const platformOrderNo = String(payload.platformOrderNo || payload.platform_order_no || '').trim()
  const productCode = String(payload.productCode || payload.product_code || '').trim()

  if (!platformOrderNo) {
    throw createHttpError('测试业务单号不能为空', {
      statusCode: 400,
      errorCode: 'kuaishou_feifei_missing_platform_order_no',
    })
  }

  if (!productCode) {
    throw createHttpError('feifei 商品编码不能为空', {
      statusCode: 400,
      errorCode: 'kuaishou_feifei_missing_product_code',
    })
  }

  const orderInput: Parameters<typeof createKuaishouFeifeiOrder>[0] = {
    platformOrderNo,
    productCode,
    platformBuyNum: Number(payload.platformBuyNum || payload.platform_buy_num || 1) || 1,
    playerAccount: String(payload.playerAccount || payload.player_account || '').trim(),
    playerGameRegion: String(payload.playerGameRegion || payload.player_game_region || '').trim(),
    playerGameSrv: String(payload.playerGameSrv || payload.player_game_srv || '').trim(),
    playerGameRole: String(payload.playerGameRole || payload.player_game_role || '').trim(),
    submitPlayer: payload.submitPlayer === true || payload.submit_player === true,
    notifyUrl: String(payload.notifyUrl || payload.notify_url || '').trim(),
  }
  const platformAmount = normalizeOptionalNumber(payload.platformAmount ?? payload.platform_amount)

  if (platformAmount !== undefined) {
    orderInput.platformAmount = platformAmount
  }

  return createKuaishouFeifeiOrder(orderInput)
}

export async function queryAdminKuaishouFeifeiTestOrder(payload: JsonObject = {}) {
  const platformOrderNo = String(payload.platformOrderNo || payload.platform_order_no || '').trim()
  const orderNo = String(payload.orderNo || payload.order_no || '').trim()

  if (!platformOrderNo && !orderNo) {
    throw createHttpError('请填写 feifei 平台单号或测试业务单号', {
      statusCode: 400,
      errorCode: 'kuaishou_feifei_missing_order_query',
    })
  }

  return queryKuaishouFeifeiOrder({
    platformOrderNo,
    orderNo,
  })
}

function getAdminEditableKuaishouFeifeiConfig() {
  if (hasKuaishouFeifeiConfigFile()) {
    return getKuaishouFeifeiSourceConfig()
  }

  return normalizeKuaishouFeifeiSourceConfig(getKuaishouFeifeiConfig())
}

function mapEffectiveKuaishouFeifeiConfig(config: ReturnType<typeof getKuaishouFeifeiConfig>) {
  return {
    enabled: config.enabled !== false,
    baseUrl: config.baseUrl,
    timeoutMs: config.timeoutMs,
    notifyUrl: config.notifyUrl,
    hasAppKey: Boolean(config.appKey),
    hasAppSecret: Boolean(config.appSecret),
    productRuleCount: config.productRules.length,
  }
}

async function listAllKuaishouFeifeiProducts(input: { status: string; supplyProductName: string }) {
  const perPage = 100
  const firstPage = await listKuaishouFeifeiProducts({
    page: 1,
    perPage,
    status: input.status,
    supplyProductName: input.supplyProductName,
  })
  const products = [...firstPage.items]
  const total = Number(firstPage.total || products.length) || products.length
  const pageCount = Math.max(1, Math.ceil(total / perPage))

  for (let page = 2; page <= pageCount; page += 1) {
    const result: KuaishouFeifeiProductListResult = await listKuaishouFeifeiProducts({
      page,
      perPage,
      status: input.status,
      supplyProductName: input.supplyProductName,
    })
    products.push(...result.items)
  }

  return products
}

function normalizeOptionalNumber(value: unknown) {
  if (value == null || String(value).trim() === '') {
    return undefined
  }

  const numberValue = Number(value)
  return Number.isFinite(numberValue) ? numberValue : undefined
}
