import { runtimeConfig } from '../../config/runtime.js'
import { createHttpError } from '../../utils/http.js'
import type { RuntimeConfig } from '../../types/runtime-config.js'

export const OPEN_91_PROVIDER = '91kaquan'
export const OPEN_91_PLATFORM = 'kuaishou'
export const OPEN_91_SUCCESS_MESSAGE = '接口调用成功'
export const OPEN_91_DEFAULT_FAIL_CODE = 1204
export const OPEN_91_COST_EXCEED_FAIL_CODE = 1220

type Open91RuntimeConfig = RuntimeConfig['platforms']['ninetyone']

export function getOpen91Config(overrides: Partial<Open91RuntimeConfig> = {}) {
  const config = {
    ...(runtimeConfig.platforms?.ninetyone || {}),
    ...overrides,
  }

  return {
    userId: String(config.userId || '').trim(),
    secret: String(config.secret || '').trim(),
    version: String(config.version || '1.0').trim() || '1.0',
    shopId: String(config.shopId || OPEN_91_PROVIDER).trim() || OPEN_91_PROVIDER,
    shopName: String(config.shopName || '91卡券').trim() || '91卡券',
    timestampToleranceSeconds: Number(config.timestampToleranceSeconds || 600) || 600,
    cardsEncoding:
      String(config.cardsEncoding || 'aes-256-ecb-base64').trim() || 'aes-256-ecb-base64',
  }
}

export function assertOpen91Config() {
  const config = getOpen91Config()

  if (!config.secret) {
    throw createHttpError('91卡券 secret 未配置', {
      statusCode: 500,
      errorCode: 'open91_missing_secret',
    })
  }

  if (config.secret.length !== 32) {
    throw createHttpError('91卡券 secret 长度必须为 32 个字符', {
      statusCode: 500,
      errorCode: 'open91_invalid_secret_length',
    })
  }

  return config
}
