'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('fs');
const os = require('os');
const path = require('path');
const { extractFaqFromLdJson, extractFaqFromNuxt } = require('../src/faq-fetcher');
const { updateMarkdownFile } = require('../src/faq-update');
test('faq: extracts FAQPage JSON-LD questions', () => {
const html = ``;
const qs = extractFaqFromLdJson(html);
assert.deepEqual(qs, [{ q: 'Q1?', a: 'A1' }, { q: 'Q2?', a: 'A2' }]);
});
test('faq: updates existing answer and appends new question', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'kb-faq-'));
const file = path.join(dir, '01.md');
fs.writeFileSync(file, '---\ntitle: T\n---\n### Q: Old?\nold answer\n');
const r = updateMarkdownFile(file, [{ q: 'Old?', a: 'new answer' }, { q: 'New?', a: 'new q answer' }]);
assert.equal(r.changed, true);
assert.equal(r.updated, 1);
assert.equal(r.added, 1);
const out = fs.readFileSync(file, 'utf8');
assert.match(out, /Old\?\nnew answer/);
assert.match(out, /New\?\nnew q answer/);
});
test('faq: normalized question match avoids duplicate append', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'kb-faq-norm-'));
const file = path.join(dir, '01.md');
fs.writeFileSync(file, '---\ntitle: T\n---\n### Q: How does Brexit affect shipping\nold\n');
const r = updateMarkdownFile(file, [{ q: 'How does Brexit affect shipping?', a: 'new' }]);
assert.equal(r.added, 0);
assert.equal(r.updated, 1);
const out = fs.readFileSync(file, 'utf8');
assert.equal((out.match(/### Q:/g) || []).length, 1);
assert.match(out, /new/);
});
test('faq: extracts FAQ from Nuxt SSR payload (no JSON-LD)', () => {
const html = '';
const qs = extractFaqFromNuxt(html);
assert.deepEqual(qs, [{ q: 'Q1?', a: 'A1' }, { q: 'Q2?', a: 'A2 & more' }]);
});
test('faq: nuxt extractor tolerates missing/broken payload', () => {
assert.deepEqual(extractFaqFromNuxt('no payload'), []);
assert.deepEqual(extractFaqFromNuxt(''), []);
});