import { APP_CONFIG_KEYS } from '../../config/app-config-keys.js'
import type { JsonObject } from '../../types/json.js'
import { readAppConfigEntry, saveAppConfigEntry } from '../config/app-config-store.js'

export type WorkerProductMatchConfig = {
  legacyFallbackEnabled: boolean
}

export function getWorkerProductMatchConfig(): WorkerProductMatchConfig {
  return readAppConfigEntry({
    configKey: APP_CONFIG_KEYS.workerProductMatch,
    fallback: createDefaultWorkerProductMatchConfig,
    normalize: normalizeWorkerProductMatchConfig,
  })
}

export async function saveWorkerProductMatchConfig(
  rawValue: unknown,
): Promise<WorkerProductMatchConfig> {
  return saveAppConfigEntry({
    configKey: APP_CONFIG_KEYS.workerProductMatch,
    value: rawValue,
    normalize: normalizeWorkerProductMatchConfig,
  })
}

export function createDefaultWorkerProductMatchConfig(): WorkerProductMatchConfig {
  return { legacyFallbackEnabled: false }
}

export function normalizeWorkerProductMatchConfig(rawValue: unknown): WorkerProductMatchConfig {
  const source = isPlainObject(rawValue) ? rawValue : {}
  return {
    // 默认关闭旧规则，避免大标题中的公共词触发错误接单。
    legacyFallbackEnabled:
      typeof source.legacyFallbackEnabled === 'boolean' ? source.legacyFallbackEnabled : false,
  }
}

function isPlainObject(value: unknown): value is JsonObject {
  return Object.prototype.toString.call(value) === '[object Object]'
}
