import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
import { fileURLToPath } from 'node:url'

import { compileScript, compileTemplate, parse } from '@vue/compiler-sfc'

import {
  fetchFinancialConnectorObservability,
  fetchFinancialPaymentEvidence
} from '../src/services/financialConnectors.js'

const panelPath = fileURLToPath(new URL('../src/components/dashboard/FinancialConnectorHealthPanel.vue', import.meta.url))
const panelSource = readFileSync(panelPath, 'utf8')
const overviewSource = readFileSync(
  fileURLToPath(new URL('../src/views/OverviewView.vue', import.meta.url)),
  'utf8'
)

test('连接器观测与付款证据接口使用租户内路径并限制窗口', async () => {
  const requests = []
  const originalFetch = globalThis.fetch
  globalThis.fetch = async (url) => {
    requests.push(String(url))
    return new Response(JSON.stringify({ summary: {}, items: [] }), {
      status: 200,
      headers: { 'content-type': 'application/json' }
    })
  }
  try {
    await fetchFinancialConnectorObservability({ windowHours: 999 })
    await fetchFinancialPaymentEvidence('claim/a')
  } finally {
    globalThis.fetch = originalFetch
  }

  assert.equal(requests[0], '/api/v1/financial-connectors/observability?window_hours=720')
  assert.equal(requests[1], '/api/v1/financial-connectors/payment-evidence/claim%2Fa')
  await assert.rejects(() => fetchFinancialPaymentEvidence(''), /不能为空/u)
})

test('连接器健康面板可以独立编译并接入财务看板', () => {
  const parsed = parse(panelSource, { filename: panelPath })
  assert.deepEqual(parsed.errors, [])
  const script = compileScript(parsed.descriptor, { id: 'financial-connector-health-panel' })
  const template = compileTemplate({
    source: parsed.descriptor.template?.content || '',
    filename: panelPath,
    id: 'financial-connector-health-panel',
    compilerOptions: { bindingMetadata: script.bindings }
  })
  assert.deepEqual(template.errors, [])
  assert.match(overviewSource, /<FinancialConnectorHealthPanel/u)
  assert.match(overviewSource, /activeDashboard === 'finance'/u)
})

test('面板明确区分证据等级且不把未采集运行指标伪装成零', () => {
  assert.match(panelSource, /生产外部回执 · 高可信现金事实/u)
  assert.match(panelSource, /人工付款确认 · 低等级内部状态/u)
  assert.match(panelSource, /模拟\/预发布回执 · 仅验证，不入核心账/u)
  assert.match(panelSource, /retry_count == null \? '待耐久遥测'/u)
  assert.match(panelSource, /signature_failure_count == null \? '待耐久遥测'/u)
  assert.doesNotMatch(panelSource, /raw_payload|signature_header|secret_ref/u)
})
