import test from 'node:test'
import assert from 'node:assert/strict'
import path from 'node:path'

import { applyEnvOverrides, ENV_OVERRIDES } from './env-overrides.js'
import type { RuntimeConfig } from '../types/runtime-config.js'

test('applyEnvOverrides maps typed environment values without mutating base config', () => {
  const baseConfig = createRuntimeConfig()

  const config = applyEnvOverrides(baseConfig, {
    PORT: '4000',
    TENCENT_BROWSER_HEADLESS: 'true',
    TENCENT_BROWSER_SLOW_MO: '250',
    TENCENT_BROWSER_VNC_RESOLUTION: '1920x1080x24',
    DATA_ROOT: './tmp/backend-data',
    DATABASE_SSL: 'yes',
    ADMIN_DEFAULT_USERS_JSON: '[{"username":"admin","password":"secret","role":"admin"}]',
    AGISO_TRADE_DETAIL_TIMEOUT_MS: '7000',
    CLOUDTENTACLES_DEVICE_TYPE: '3',
    TENCENT_REDEEM_PROOF_MODE: 'basic',
  })

  assert.equal(config.server.port, 4000)
  assert.equal(config.browser.headless, true)
  assert.equal(config.browser.slowMoMs, 250)
  assert.equal(config.browser.vncResolution, '1920x1080x24')
  assert.equal(config.data.root, path.resolve('./tmp/backend-data'))
  assert.equal(config.database.ssl, true)
  assert.deepEqual(config.admin.defaultUsers, [
    { username: 'admin', password: 'secret', role: 'admin' },
  ])
  assert.equal(config.platforms.agiso.tradeDetail.timeoutMs, 7000)
  assert.equal(config.platforms.cloudtentacles.deviceType, 3)
  assert.equal(config.redeem.proofMode, 'basic')

  assert.equal(baseConfig.server.port, 3000)
  assert.equal(baseConfig.browser.headless, null)
  assert.deepEqual(baseConfig.admin.defaultUsers, [])
})

test('applyEnvOverrides derives claim base url from app base url when explicit claim url is absent', () => {
  const config = applyEnvOverrides(createRuntimeConfig(), {
    APP_BASE_URL: 'https://example.test///',
  })

  assert.equal(config.orders.claimBaseUrl, 'https://example.test/#/claim')
})

test('applyEnvOverrides prefers explicit claim base url over app base url', () => {
  const config = applyEnvOverrides(createRuntimeConfig(), {
    APP_BASE_URL: 'https://example.test',
    CLAIM_BASE_URL: 'https://claim.example.test/custom',
  })

  assert.equal(config.orders.claimBaseUrl, 'https://claim.example.test/custom')
})

test('applyEnvOverrides ignores empty or invalid values', () => {
  const config = applyEnvOverrides(createRuntimeConfig(), {
    PORT: 'not-a-number',
    DATABASE_SSL: 'maybe',
    ADMIN_DEFAULT_USERS_JSON: '{"username":"admin"}',
    LOG_LEVEL: '   ',
  })

  assert.equal(config.server.port, 3000)
  assert.equal(config.database.ssl, false)
  assert.deepEqual(config.admin.defaultUsers, [])
  assert.equal(config.logging.level, 'info')
})

test('ENV_OVERRIDES keeps environment variable names unique', () => {
  const names = ENV_OVERRIDES.map((override) => override.env)
  assert.equal(new Set(names).size, names.length)
})

function createRuntimeConfig(): RuntimeConfig {
  return {
    server: {
      port: 3000,
    },
    browser: {
      chromePath: '',
      headless: null,
      devtools: null,
      keepAlive: null,
      prewarm: null,
      slowMoMs: null,
      vncResolution: '1600x900x24',
    },
    session: {
      debug: false,
    },
    ocr: {
      baseUrl: '',
    },
    data: {
      root: '/tmp/order-site',
    },
    logging: {
      level: 'info',
    },
    database: {
      url: 'postgres://postgres:postgres@127.0.0.1:5432/order_site',
      ssl: false,
      maxConnections: 10,
    },
    orders: {
      claimBaseUrl: 'http://127.0.0.1:5173/#/claim',
      tokenTtlHours: 24,
    },
    admin: {
      sessionSecret: '',
      sessionTtlHours: 12,
      defaultUsers: [],
    },
    platforms: {
      agiso: {
        appSecret: '',
        tradeDetail: {
          endpoint: 'https://gw-api.agiso.com/aldsIdle/Order/Detail',
          apiVersion: '1',
          timeoutMs: 5000,
        },
        autoDelivery: {
          enabled: true,
          endpoint: 'https://gw-api.agiso.com/aldsIdle/Order/DummySend',
          apiVersion: '1',
        },
        messaging: {
          enabled: false,
          sendMessageEndpoint: 'https://gw-api.agiso.com/aldsIdle/ImMsg/SendMsg',
          apiVersion: '1',
          messageTemplate: '',
          autoDeliveryMessageTemplate: '',
          shops: {},
        },
      },
      ninetyone: {
        userId: '',
        secret: '',
        version: '1.0',
        shopId: '91kaquan',
        shopName: '91卡券',
        timestampToleranceSeconds: 600,
        cardsEncoding: 'aes-256-ecb-base64',
      },
      cloudtentacles: {
        baseUrl: 'https://123.207.217.176',
        timeoutMs: 5000,
        sendSmsPath: '/public/verif_code',
        loginPath: '/public/login',
        userInfoPath: '/user/info',
        assetPath: '/user/get_asset',
        permissionPath: '/user/get_permission',
        categoriesPath: '/categories/get',
        skuListPath: '/sku/list',
        skuBuyPath: '/sku/buy',
        skuUsePath: '/sku/use',
        knapsackPath: '/user/get_knapsack',
        vnListPath: '/vn/list',
        vnAppointPath: '/vn/appoint',
        vnGenerateLoginCodePath: '/vn/generate_login_code',
        vnVerifCodePath: '/public/vn_verif_code',
        vnVerifyLoginCodePath: '/vn/verify_login_code',
        vnBindUrlPath: '/vn/bind_url',
        vnBindInfoPath: '/vn/bind_info',
        vnBackPath: '/vn/back',
        bindUrlTtlSeconds: 600,
        bindUrlProbeIntervalSeconds: 30,
        bindUrlProbeTimeoutMs: 5000,
        bindUrlProbeUserAgent: '',
        bindUrlProbeEndpoint: 'https://comm.ams.game.qq.com/ide/',
        bindUrlProbeChartId: '323794',
        bindUrlProbeSubChartId: '323794',
        bindUrlProbeIdeToken: 'z90Syo',
        bindUrlProbeActivityUrl: '',
        bindUrlProbeReferer: 'https://gp.qq.com/',
        bindUrlProbeExtraCookie: '',
        publicKeyPem: '',
        clientSource: 'ct-client',
        deviceId: '-',
        deviceType: 0,
      },
    },
    redeem: {
      proofMode: 'full',
    },
  }
}
