import assert from "node:assert/strict";
import test from "node:test";

import {
  API,
  API_STORAGE_KEY,
  DEFAULT_API,
  resolveApiBase,
} from "../src/components/config.js";

test("api base keeps the script default outside the browser", () => {
  assert.equal(API, DEFAULT_API);
  assert.equal(resolveApiBase({location: null, storage: null}), DEFAULT_API);
});

test("api base follows the dashboard host in the browser", () => {
  assert.equal(
    resolveApiBase({
      location: new URL("http://localhost:3000/workstreams"),
      storage: null,
    }),
    "http://localhost:8000",
  );
  assert.equal(
    resolveApiBase({
      location: new URL("http://statehub.local:3000/workstreams"),
      storage: null,
    }),
    "http://statehub.local:8000",
  );
});

test("api base supports explicit query and storage overrides", () => {
  assert.equal(
    resolveApiBase({
      location: new URL("http://localhost:3000/?api_base=http%3A%2F%2F127.0.0.1%3A18000%2F"),
      storage: {
        getItem: () => "http://ignored.example:8000",
      },
    }),
    "http://127.0.0.1:18000",
  );
  assert.equal(
    resolveApiBase({
      location: new URL("http://localhost:3000/"),
      storage: {
        getItem: key => key === API_STORAGE_KEY ? " http://127.0.0.1:18000/ " : null,
      },
    }),
    "http://127.0.0.1:18000",
  );
});

test("ipv6 loopback dashboards use the ipv4 api default", () => {
  assert.equal(
    resolveApiBase({
      location: new URL("http://[::1]:3000/"),
      storage: null,
    }),
    DEFAULT_API,
  );
});
