const apiBase = (process.env.API_BASE || 'http://localhost:4000/api').replace(/\/+$/, '')
const webBase = (process.env.WEB_BASE || process.env.FRONTEND_ORIGIN || 'http://localhost:3000').replace(/\/+$/, '')
const localDevAdminToken = ['dev', 'admin', 'token'].join('-')
const adminToken = process.env.ADMIN_TOKEN || (process.env.NODE_ENV === 'production' ? '' : localDevAdminToken)
const strictCorsExpected = process.env.EXPECT_STRICT_CORS === 'true' || process.env.NODE_ENV === 'production'
const runIp = process.env.TEST_CLIENT_IP || `127.44.${Math.max(1, Date.now() % 240)}.${Math.max(1, process.pid % 240)}`

function assert(condition, message) {
  if (!condition) throw new Error(message)
}

async function api(path, options = {}) {
  const response = await fetch(`${apiBase}${path}`, {
    ...options,
    headers: {
      'content-type': 'application/json',
      'x-forwarded-for': runIp,
      ...(options.headers || {}),
    },
  })
  const text = await response.text()
  const data = text ? JSON.parse(text) : null
  if (!response.ok) {
    const error = new Error(data?.message || `${path} failed with ${response.status}`)
    error.status = response.status
    error.data = data
    throw error
  }
  return data
}

async function assertBackendHealth() {
  const health = await api('/health/deep')
  assert(['ok', 'degraded'].includes(health.status), `deep health 状态异常：${health.status}`)
  const storage = health.checks?.objectStorage || health.checks?.object_storage
  assert(storage, 'deep health 缺少 objectStorage 检查')
  if (storage.driver === 'local') {
    assert(storage.status === 'ok', '本地对象存储模式不应显示错误')
  }
  console.log(`✓ deep health: ${health.status}`)
}

async function assertConfigChecks() {
  const checks = await api('/admin/system/config-checks', {
    headers: adminToken ? { 'x-admin-token': adminToken } : {},
  })
  const byKey = new Map((checks.items || []).map((item) => [item.key, item]))
  for (const key of ['cors', 'rate_limit', 'api_internal_url', 'public_api_base_url', 'object_storage', 'wechat_pay']) {
    assert(byKey.has(key), `配置检查缺少 ${key}`)
  }
  if (process.env.NODE_ENV === 'production') {
    assert(byKey.get('cors')?.status !== 'warning', '生产环境 CORS 不应是开放警告态')
    assert(byKey.get('api_internal_url')?.status === 'ok', '生产环境必须配置 API_INTERNAL_URL')
  }
  console.log('✓ 配置检查项完整')
}

async function assertCorsPolicy() {
  const response = await fetch(`${apiBase}/health`, {
    headers: {
      Origin: 'https://not-allowed.example.invalid',
      'x-forwarded-for': runIp,
    },
  })
  if (strictCorsExpected) {
    assert(response.status === 403, `严格 CORS 下非白名单 Origin 应返回 403，实际 ${response.status}`)
    console.log('✓ CORS 非白名单拒绝')
    return
  }
  assert(response.ok, '本地开发 CORS 应允许健康检查')
  console.log('✓ 本地 CORS 开放符合开发预期')
}

async function assertSsrPages() {
  const pages = [
    { path: '/', content: /近期课程|近期活动|关于研究院/ },
    { path: '/about', content: /关于我们|关于研究院/ },
    { path: '/consulting', content: /规划咨询/ },
    { path: '/data', content: /数据服务/ },
    { path: '/courses', content: /课程目录|暂无课程|推荐课程/ },
    { path: '/events', content: /活动|报名/ },
    { path: '/experts', content: /专家平台/ },
    { path: '/news', content: /新闻资讯|暂无已发布资讯|资讯/ },
  ]
  for (const { path, content } of pages) {
    const response = await fetch(`${webBase}${path}`)
    const text = await response.text()
    assert(response.status === 200, `${path} SSR 应返回 200，实际 ${response.status}`)
    assert(content.test(text), `${path} SSR 缺少页面关键内容`)
    assert(!/ERR_INVALID_URL|Failed to parse URL from \/api/i.test(text), `${path} 出现 SSR 内部 API 相对地址错误`)
  }
  console.log(`✓ SSR 页面通过：${pages.map((item) => item.path).join(', ')}`)
}

async function assertSmallUploadProbe() {
  if (process.env.PRODUCTION_READINESS_WRITE !== 'true') {
    console.log('· 跳过对象存储轻写探测：设置 PRODUCTION_READINESS_WRITE=true 可启用')
    return
  }
  const response = await fetch(`${apiBase}/admin/uploads/raw`, {
    method: 'POST',
    headers: {
      ...(adminToken ? { 'x-admin-token': adminToken } : {}),
      'x-file-name': encodeURIComponent(`production-readiness-${Date.now()}.txt`),
      'content-type': 'text/plain',
      'x-forwarded-for': runIp,
    },
    body: Buffer.from('production readiness probe'),
  })
  const text = await response.text()
  const data = text ? JSON.parse(text) : null
  assert(response.ok && data?.id, `对象存储轻写探测失败：${response.status}`)
  console.log('✓ 对象存储轻写探测通过')
}

async function main() {
  console.log(`生产配置验收：api=${apiBase} web=${webBase}`)
  await assertBackendHealth()
  await assertConfigChecks()
  await assertCorsPolicy()
  await assertSsrPages()
  await assertSmallUploadProbe()
  console.log('生产配置验收通过')
}

main().catch((error) => {
  console.error(error.stack || error.message)
  if (error.data) console.error(JSON.stringify(error.data, null, 2))
  process.exit(1)
})
