import test from "node:test";
import assert from "node:assert/strict";
import { getApiBase, normalizeServerOrigin, readSavedServerOrigin, writeSavedServerOrigin } from "./api-base.js";

test("uses same-origin api path by default", () => {
  assert.equal(getApiBase(), "/api");
});

test("allows an explicit api url", () => {
  assert.equal(getApiBase("https://example.test/api"), "https://example.test/api");
});

test("native api uses the saved PC origin", () => {
  const storage = { getItem: () => "https://codex.example.ts.net" };

  assert.equal(getApiBase(undefined, { isNative: true, storage }), "https://codex.example.ts.net/api");
  assert.equal(getApiBase(undefined, { isNative: false, storage }), "/api");
});

test("normalizes only secure server origins without credentials or paths", () => {
  assert.equal(normalizeServerOrigin(" codex.example.ts.net/ "), "https://codex.example.ts.net");
  assert.equal(normalizeServerOrigin("https://codex.example.ts.net"), "https://codex.example.ts.net");
  assert.throws(() => normalizeServerOrigin("http://codex.example.ts.net"), /secure_server_required/);
  assert.throws(() => normalizeServerOrigin("https://user:secret@codex.example.ts.net"), /invalid_server_address/);
  assert.throws(() => normalizeServerOrigin("https://codex.example.ts.net/private"), /invalid_server_address/);
});

test("saved PC origin persistence fails closed", () => {
  const values = new Map();
  const storage = {
    getItem: (key) => values.get(key),
    setItem: (key, value) => values.set(key, value)
  };

  writeSavedServerOrigin(storage, "codex.example.ts.net");
  assert.equal(readSavedServerOrigin(storage), "https://codex.example.ts.net");
  values.set("codexRemote.serverOrigin", "javascript:alert(1)");
  assert.equal(readSavedServerOrigin(storage), "");
});
