import { getAgisoShopConfig } from '../../platforms/agiso/shop-config-service.js'
import {
  filterLegacyOrderFulfillmentBindings,
  getOrderFulfillmentBindingsFilePath,
  getLegacyOrderFulfillmentBindingConfigs,
  saveOrderFulfillmentBindingConfigs,
} from '../../order/fulfillment-binding-config-service.js'
import { enrichAgisoXianyuTradeOrder } from '../../platforms/agiso/xianyu/order-detail-service.js'
import { syncConfiguredFulfillmentBindings } from '../../bootstrap/fulfillment-bootstrap-service.js'
import { getFulfillmentProfileByKey } from '../../../repositories/fulfillment-profile-repo.js'
import { createHttpError } from '../../../utils/http.js'
import {
  buildFulfillmentLookupResult,
  normalizeFulfillmentLookupPayload,
  resolveFulfillmentLookupDetail,
} from './fulfillment.js'
import { listAdminObservedProducts } from './observed-products.js'
import { validateAdminFulfillmentBindingConfigs } from './validation.js'
import { mapAdminFulfillmentBindingConfigItem } from './domain.js'

import type {
  AdminFulfillmentBindingConfigSaveInput,
  AdminFulfillmentBindingLookupInput,
} from '../../../types/admin-write-inputs.js'

type JsonObject = Record<string, any>

export async function getAdminFulfillmentBindingConfigs() {
  const bindings = getLegacyOrderFulfillmentBindingConfigs()

  return {
    filePath: getOrderFulfillmentBindingsFilePath(),
    bindings: bindings.map(mapAdminFulfillmentBindingConfigItem),
    observedProducts: await listAdminObservedProducts(bindings),
  }
}

export async function lookupAdminFulfillmentBindingOrder(
  payload: AdminFulfillmentBindingLookupInput = {},
) {
  const { provider, platform, shopId, platformOrderId } = normalizeFulfillmentLookupPayload(payload)

  const detailResult = await enrichAgisoXianyuTradeOrder({
    provider,
    platform,
    shopId,
    shopName: '',
    platformOrderId,
    orderStatus: 'created',
    payStatus: 'unpaid',
    buyerId: '',
    buyerName: '',
    receiverContact: '',
    totalAmount: 0,
    currency: 'CNY',
    paidAt: null,
    rawPayload: {},
    items: [],
  }, {
    requestId: `admin-fulfillment-lookup:${shopId}:${platformOrderId}`,
  })

  const { detail } = resolveFulfillmentLookupDetail(detailResult, platformOrderId)
  const bindings = getLegacyOrderFulfillmentBindingConfigs()
  return buildFulfillmentLookupResult({
    provider,
    platform,
    shopId,
    platformOrderId,
    detail,
    detailResult,
    bindings,
    fallbackShopName: getAgisoShopConfig(shopId)?.shopName,
  })
}

export async function updateAdminFulfillmentBindingConfigs(
  payload: AdminFulfillmentBindingConfigSaveInput = {},
) {
  const bindingsInput = Array.isArray(payload.bindings) ? payload.bindings : []
  const normalizedBindings = await validateAdminFulfillmentBindingConfigs(bindingsInput, {
    getFulfillmentProfileByKey,
  })
  assertLegacyBindingConfigsOnly(normalizedBindings)
  const saved = saveOrderFulfillmentBindingConfigs(normalizedBindings)
  await syncConfiguredFulfillmentBindings()

  return {
    filePath: getOrderFulfillmentBindingsFilePath(),
    bindings: saved.map(mapAdminFulfillmentBindingConfigItem),
  }
}

function assertLegacyBindingConfigsOnly(bindings: JsonObject[] = []) {
  if (filterLegacyOrderFulfillmentBindings(bindings).length === bindings.length) {
    return
  }

  throw createHttpError('快手履约规则请改到“快手 Cloud 新履约”页维护，旧履约规则仅保留给 Agiso 等历史场景', {
    statusCode: 400,
    errorCode: 'admin_fulfillment_bindings_kuaishou_cloud_moved',
  })
}
