"use strict";
const assert = require("node:assert/strict");
const test = require("node:test");
const { createServer, loadMap, search } = require("./server");

test("repository map has unique sequential codes and domestic primary routes", () => {
  const map = loadMap();
  assert.equal(map.repositories.length, 8);
  assert.deepEqual(map.repositories.map(item => item.code), ["REPO-001","REPO-002","REPO-003","REPO-004","REPO-005","REPO-006","REPO-007","REPO-008"]);
  assert.equal(new Set(map.repositories.map(item => item.code)).size, 8);
  for (const item of map.repositories) assert.match(item.primary.url, /^https:\/\/guanghulab\.com\/fifth-domain\//);
});

test("Chinese language-world query resolves the Fifth Domain primary", () => {
  const results = search(loadMap(), "光湖语言世界 第五域");
  assert.equal(results[0].code, "REPO-001");
  assert.equal(results[0].state, "DOMESTIC_PRIMARY");
});

test("public endpoints are read-only and expose CORS", async () => {
  const server = createServer();
  await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
  const base = `http://127.0.0.1:${server.address().port}`;
  try {
    const response = await fetch(`${base}/v1/resolve?id=REPO-004`);
    assert.equal(response.status, 200);
    assert.equal(response.headers.get("access-control-allow-origin"), "*");
    assert.equal((await response.json()).slug, "guanghu");
    assert.equal((await fetch(`${base}/v1/search`, { method: "POST" })).status, 405);
  } finally { await new Promise(resolve => server.close(resolve)); }
});
