const { describe, it } = require('node:test')
const assert = require('node:assert/strict')
const {
  extractNewContentId,
  detectEdgeChallengeResponse,
  buildEdgeChallengeUserMessage,
} = require('./api')

describe('extractNewContentId', () => {
  it('reads id from JSON body', () => {
    assert.equal(extractNewContentId({ data: { id: 'abc-123' } }), 'abc-123')
  })

  it('parses id from string body URL', () => {
    assert.equal(
      extractNewContentId({ data: 'https://cms.example/api/apps/x/contents/foo-bar/' }),
      'foo-bar',
    )
  })

  it('parses id from Location header', () => {
    assert.equal(
      extractNewContentId({
        data: {},
        headers: { location: '/api/apps/app1/contents/new-id' },
      }),
      'new-id',
    )
  })

  it('returns null when id cannot be determined', () => {
    assert.equal(extractNewContentId({ data: { ok: true } }), null)
    assert.equal(extractNewContentId(null), null)
  })
})

describe('detectEdgeChallengeResponse', () => {
  it('detects Cloudflare HTML challenge pages', () => {
    const res = {
      headers: { 'content-type': 'text/html; charset=UTF-8', 'cf-ray': 'abc-SJC' },
    }
    const result = detectEdgeChallengeResponse(res, '<html></html>')
    assert.equal(result.likely, true)
    assert.equal(result.reason, 'cf-ray+text/html')
  })

  it('does not flag normal JSON errors as WAF', () => {
    const res = { headers: { 'content-type': 'application/json' } }
    const result = detectEdgeChallengeResponse(res, { message: 'Forbidden' })
    assert.equal(result.likely, false)
  })
})

describe('buildEdgeChallengeUserMessage', () => {
  it('includes status, ray id, and support contact', () => {
    const message = buildEdgeChallengeUserMessage(403, { headers: { 'cf-ray': 'x123-ORD' } })
    assert.match(message, /403/)
    assert.match(message, /x123-ORD/)
    assert.match(message, /support@bildit\.co/i)
  })
})
