import { runtimeConfig } from '../../../config/runtime.js'
import { createHttpError } from '../../../utils/http.js'
import type { RuntimeConfig } from '../../../types/runtime-config.js'
import {
  getKuaishouFeifeiSourceConfig,
  hasKuaishouFeifeiConfigFile,
} from './source-config-service.js'

export const KUAISHOU_FEIFEI_EXECUTOR_KEY = 'kuaishou_feifei'
export const KUAISHOU_FEIFEI_PROFILE_KEY = 'kuaishou_feifei'

type KuaishouFeifeiRuntimeConfig = RuntimeConfig['platforms']['kuaishouFeifei']

export function getKuaishouFeifeiConfig(overrides: Partial<KuaishouFeifeiRuntimeConfig> = {}) {
  const runtimeValue = runtimeConfig.platforms?.kuaishouFeifei || {}
  const savedValue = hasKuaishouFeifeiConfigFile() ? getKuaishouFeifeiSourceConfig() : null
  const config = mergeKuaishouFeifeiConfig(runtimeValue, savedValue, overrides)

  return {
    enabled: config.enabled !== false,
    baseUrl: String(config.baseUrl || 'http://skin-exchange.yiquyou.icu')
      .trim()
      .replace(/\/+$/, ''),
    appKey: String(config.appKey || '').trim(),
    appSecret: String(config.appSecret || '').trim(),
    timeoutMs: Math.max(1, Number(config.timeoutMs || 10000) || 10000),
    notifyUrl: String(config.notifyUrl || '').trim(),
    productRules: Array.isArray(config.productRules) ? config.productRules : [],
  }
}

export function assertKuaishouFeifeiConfig() {
  const config = getKuaishouFeifeiConfig()

  if (config.enabled === false) {
    throw createHttpError('kuaishou-feifei 已停用', {
      statusCode: 409,
      errorCode: 'kuaishou_feifei_disabled',
    })
  }

  if (!config.baseUrl) {
    throw createHttpError('kuaishou-feifei baseUrl 未配置', {
      statusCode: 500,
      errorCode: 'kuaishou_feifei_missing_base_url',
    })
  }

  if (!config.appKey || !config.appSecret) {
    throw createHttpError('kuaishou-feifei App Key / App Secret 未配置', {
      statusCode: 500,
      errorCode: 'kuaishou_feifei_missing_credential',
    })
  }

  return config
}

function mergeKuaishouFeifeiConfig(
  runtimeValue: Partial<KuaishouFeifeiRuntimeConfig>,
  savedValue: Partial<KuaishouFeifeiRuntimeConfig> | null,
  overrides: Partial<KuaishouFeifeiRuntimeConfig>,
): KuaishouFeifeiRuntimeConfig {
  const base: KuaishouFeifeiRuntimeConfig = savedValue
    ? {
        enabled: savedValue.enabled !== false,
        baseUrl: savedValue.baseUrl || runtimeValue.baseUrl || 'http://skin-exchange.yiquyou.icu',
        appKey: savedValue.appKey || runtimeValue.appKey || '',
        appSecret: savedValue.appSecret || runtimeValue.appSecret || '',
        timeoutMs: savedValue.timeoutMs || runtimeValue.timeoutMs || 10000,
        notifyUrl: savedValue.notifyUrl || runtimeValue.notifyUrl || '',
        productRules: Array.isArray(savedValue.productRules)
          ? savedValue.productRules
          : runtimeValue.productRules || [],
      }
    : {
        enabled: runtimeValue.enabled !== false,
        baseUrl: runtimeValue.baseUrl || 'http://skin-exchange.yiquyou.icu',
        appKey: runtimeValue.appKey || '',
        appSecret: runtimeValue.appSecret || '',
        timeoutMs: runtimeValue.timeoutMs || 10000,
        notifyUrl: runtimeValue.notifyUrl || '',
        productRules: runtimeValue.productRules || [],
      }

  return {
    enabled: overrides.enabled ?? base.enabled,
    baseUrl: overrides.baseUrl ?? base.baseUrl,
    appKey: overrides.appKey ?? base.appKey,
    appSecret: overrides.appSecret ?? base.appSecret,
    timeoutMs: overrides.timeoutMs ?? base.timeoutMs,
    notifyUrl: overrides.notifyUrl ?? base.notifyUrl,
    productRules: overrides.productRules ?? base.productRules,
  }
}
