import assert from "node:assert/strict";
import test from "node:test";
import {readFileSync} from "node:fs";
import {dirname, join} from "node:path";
import {fileURLToPath} from "node:url";

import {
  DEFAULT_IMPROVEMENT_DOMAIN,
  resolveImprovementApiBase,
} from "../src/components/improvement-modal.js";

const root = dirname(fileURLToPath(import.meta.url));
const modalSource = readFileSync(
  join(root, "../src/components/improvement-modal.js"),
  "utf-8",
);

test("dashboard-improvement default domain is the live infotech slug", () => {
  assert.equal(DEFAULT_IMPROVEMENT_DOMAIN, "infotech");
  // Regression: custodian was retired from the domain registry; POST /technical-debt/
  // returns 422 for unknown domain, so the shift-wait-click modal must not use it.
  assert.doesNotMatch(modalSource, /domain\s*=\s*["']custodian["']/);
  assert.match(modalSource, /domain\s*=\s*DEFAULT_IMPROVEMENT_DOMAIN/);
  assert.match(modalSource, /debt_type:\s*["']dashboard-improvement["']/);
});

test("improvement modal api base mirrors dashboard config resolution", () => {
  assert.equal(
    resolveImprovementApiBase({location: null, storage: null}),
    "http://127.0.0.1:8000",
  );
  assert.equal(
    resolveImprovementApiBase({
      location: new URL("http://localhost:3000/workstreams"),
      storage: null,
    }),
    "http://localhost:8000",
  );
  assert.equal(
    resolveImprovementApiBase({
      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",
  );
});
