import {
  getKuaishouCloudFulfillmentConfig,
  getKuaishouCloudFulfillmentFilePath,
  saveKuaishouCloudFulfillmentConfig,
} from '../../order/kuaishou-cloud-fulfillment-config-service.js'
import { syncConfiguredFulfillmentBindings } from '../../bootstrap/fulfillment-bootstrap-service.js'
import { mapAdminKuaishouCloudFulfillmentSource } from './mappers.js'

type JsonObject = Record<string, any>

export function getAdminKuaishouCloudFulfillmentConfig() {
  const config = getKuaishouCloudFulfillmentConfig()

  return {
    filePath: getKuaishouCloudFulfillmentFilePath(),
    source: mapAdminKuaishouCloudFulfillmentSource(config),
  }
}

/** @param {AdminKuaishouCloudFulfillmentConfigInput} [payload] */
export async function updateAdminKuaishouCloudFulfillmentConfig(
  payload: JsonObject = {},
) {
  const saved = saveKuaishouCloudFulfillmentConfig({
    enabled: payload.enabled !== false,
    items: Array.isArray(payload.items) ? payload.items : [],
  })

  await syncConfiguredFulfillmentBindings()

  return {
    filePath: getKuaishouCloudFulfillmentFilePath(),
    source: mapAdminKuaishouCloudFulfillmentSource(saved),
  }
}
