const test = require('node:test')
const assert = require('node:assert/strict')
const {
  detectEdgeChallengeResponse,
  buildEdgeChallengeUserMessage,
} = require('../src/lib/api')

test('detectEdgeChallengeResponse: CF ray + text/html', () => {
  const res = {
    headers: { 'content-type': 'text/html; charset=UTF-8', 'cf-ray': 'abc-SJC' },
  }
  const r = detectEdgeChallengeResponse(res, '<html></html>')
  assert.equal(r.likely, true)
  assert.equal(r.reason, 'cf-ray+text/html')
})

test('detectEdgeChallengeResponse: Just a moment HTML', () => {
  const res = {
    headers: { 'content-type': 'text/html' },
  }
  const body = '<!DOCTYPE html><html><head><title>Just a moment...</title></head></html>'
  const r = detectEdgeChallengeResponse(res, body)
  assert.equal(r.likely, true)
  assert.equal(r.reason, 'html+challenge-markers')
})

test('detectEdgeChallengeResponse: normal JSON 403 is not WAF', () => {
  const res = { headers: { 'content-type': 'application/json' } }
  const r = detectEdgeChallengeResponse(res, { message: 'Forbidden' })
  assert.equal(r.likely, false)
})

test('buildEdgeChallengeUserMessage: VEE copy and Cloudflare ray', () => {
  const res = { headers: { 'cf-ray': 'x123-ORD' } }
  const m = buildEdgeChallengeUserMessage(403, res)
  assert.match(m, /403/)
  assert.match(m, /x123-ORD/)
  assert.match(m, /Visual Experience Engine/i)
  assert.match(m, /questionable component/i)
  assert.match(m, /WAF/i)
  assert.match(m, /support@bildit\.co/i)
})
