import {
  getFulfillmentRoutingConfig,
  getFulfillmentRoutingConfigFilePath,
  saveFulfillmentRoutingConfig,
} from '../../fulfillment/routing-config-service.js'
import { resolveOrderItemForFulfillment } from '../../fulfillment/product-resolution-service.js'
import { normalizeCloudtentaclesMatchName } from '../../order/cloudtentacles-match-utils.js'
import type { JsonRecord } from '../../../types/json.js'

export function getAdminFulfillmentRoutingConfig() {
  return {
    filePath: getFulfillmentRoutingConfigFilePath(),
    ...getFulfillmentRoutingConfig(),
  }
}

export async function updateAdminFulfillmentRoutingConfig(payload: JsonRecord = {}) {
  return {
    filePath: getFulfillmentRoutingConfigFilePath(),
    ...(await saveFulfillmentRoutingConfig(payload)),
  }
}

export async function previewAdminFulfillmentRouting(payload: JsonRecord = {}) {
  const productName = String(payload.productName || payload.skuName || '').trim()
  const item = await resolveOrderItemForFulfillment({
    provider: '91kaquan',
    platform: 'kuaishou',
    item: {
      itemId: productName,
      externalItemId: productName,
      skuCode: productName,
      skuName: productName,
      externalSkuCode: productName,
      externalSkuName: productName,
      quantity: 1,
    },
  })
  const snapshot = item.snapshot || {}

  return {
    productName,
    normalizedProductName: normalizeCloudtentaclesMatchName(productName),
    resolvedSkuCode: item.skuCode,
    resolvedSkuName: item.skuName,
    isConfigured: item.isConfigured,
    fulfillmentRoute: snapshot.fulfillmentRoute || null,
    cloudtentacles: snapshot.cloudtentacles || null,
    kuaishouFeifei: snapshot.kuaishouFeifei || null,
  }
}
