import { createHttpError } from '../../../utils/http.js'
import {
  getKuaishouIndustrySourceConfig,
  type KuaishouIndustrySourceConfig,
} from './source-config-service.js'

export const KUISHOU_INDUSTRY_PROVIDER = 'kuaishou-industry'
export const KUISHOU_INDUSTRY_PLATFORM = 'kuaishou'

export function getKuaishouIndustryConfig(overrides: Partial<KuaishouIndustrySourceConfig> = {}) {
  const config = {
    ...getKuaishouIndustrySourceConfig(),
    ...overrides,
  }

  return {
    enabled: config.enabled !== false,
    baseUrl: String(config.baseUrl || '').trim(),
    authBaseUrl: String(config.authBaseUrl || '').trim(),
    redirectUri: String(config.redirectUri || '').trim(),
    scopes: String(config.scopes || '').trim(),
    authState: String(config.authState || '').trim(),
    appKey: String(config.appKey || '').trim(),
    appSecret: String(config.appSecret || '').trim(),
    signSecret: String(config.signSecret || '').trim(),
    messageSecret: String(config.messageSecret || '').trim(),
    accessToken: String(config.accessToken || '').trim(),
    refreshToken: String(config.refreshToken || '').trim(),
    accessTokenExpiresAt: String(config.accessTokenExpiresAt || '').trim(),
    refreshTokenExpiresAt: String(config.refreshTokenExpiresAt || '').trim(),
    openId: String(config.openId || '').trim(),
    grantedScopes: String(config.grantedScopes || '').trim(),
    sellerId: String(config.sellerId || '').trim(),
    lastRefreshedAt: String(config.lastRefreshedAt || '').trim(),
    lastRefreshError: String(config.lastRefreshError || '').trim(),
    provider:
      String(config.provider || KUISHOU_INDUSTRY_PROVIDER).trim() || KUISHOU_INDUSTRY_PROVIDER,
    platform:
      String(config.platform || KUISHOU_INDUSTRY_PLATFORM).trim() || KUISHOU_INDUSTRY_PLATFORM,
    shopId: String(config.shopId || KUISHOU_INDUSTRY_PROVIDER).trim() || KUISHOU_INDUSTRY_PROVIDER,
    shopName: String(config.shopName || '快手行业电子凭证').trim() || '快手行业电子凭证',
    version: String(config.version || '1').trim() || '1',
    shops: Array.isArray(config.shops) ? config.shops : [],
  }
}

export function assertKuaishouIndustryConfig() {
  const config = getKuaishouIndustryConfig()

  if (!config.appKey) {
    throw createHttpError('快手行业电子凭证 appKey 未配置', {
      statusCode: 500,
      errorCode: 'kuaishou_industry_missing_app_key',
    })
  }

  if (!config.signSecret) {
    throw createHttpError('快手行业电子凭证 signSecret 未配置', {
      statusCode: 500,
      errorCode: 'kuaishou_industry_missing_sign_secret',
    })
  }

  return config
}

export function assertMatchingAppKey(incomingAppKey: string) {
  const config = getKuaishouIndustryConfig()

  if (!config.appKey) {
    return
  }

  if (incomingAppKey !== config.appKey) {
    throw createHttpError('appkey 不匹配', {
      statusCode: 400,
      errorCode: 'kuaishou_industry_app_key_mismatch',
    })
  }
}
