const { test } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');

function read(relativePath) {
  return fs.readFileSync(path.join(__dirname, '..', relativePath), 'utf8');
}

const frontend = read('public/js/learningHub.js');
const learningAI = read('src/routes/learningAI.js');
const learningAdmin = read('src/routes/learningAdmin.js');

test('Learning AI prompts request category_name using existing categories', () => {
  assert.match(learningAI, /function buildCategoryInstruction\(existingCategories\)/);
  assert.match(learningAI, /SELECT name FROM learning_categories ORDER BY sort_order ASC, name ASC/);
  assert.match(learningAI, /"category_name": "string \(best existing category name/);
  assert.match(learningAI, /Prefer an existing category_name when it fits/);
});

test('Learning AI presentation JSON preserves generated category_name', () => {
  assert.match(learningAI, /category_name: parsedPres\.category_name \|\| ''/);
});

test('Learning Hub applies AI-generated category names to the editor', () => {
  assert.match(frontend, /return applyAiContent\(payload, contentType\)\.then/);
  assert.match(frontend, /function applyAiCategory\(categoryName\)/);
  assert.match(frontend, /sendJson\('\/api\/admin\/learning\/categories', 'POST', \{ name: categoryName \}\)/);
  assert.match(frontend, /findCategoryOption\(sel, categoryName\)/);
  assert.match(frontend, /cms\.loadCategories\(String\(data\.id\)\)/);
  assert.match(frontend, /loadCategories\(\);/);
});

test('Learning category creation is idempotent by name', () => {
  assert.match(learningAdmin, /WHERE LOWER\(name\) = LOWER\(\?\)/);
  assert.match(learningAdmin, /existing: true/);
});
