import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import test from "node:test";

import { mergeWindowsConfiguration } from "./windows-config-sync-lib.mjs";

test("Windows config sync adopts development accounts and workspaces without weakening installed security", () => {
  const installed = {
    deviceAuthentication: { required: true },
    codexCliPath: "installed-codex.cmd",
    dataDir: "installed-data",
    allowedOrigins: ["https://installed.example.ts.net"],
    accounts: [{ id: "desktop", label: "Desktop", codexHome: "desktop-home" }],
    workspaces: [{ id: "old", label: "Old", path: "old-project" }],
    futureSetting: { preserve: true }
  };
  const development = {
    deviceAuthentication: { required: false },
    codexCliPath: "development-codex.cmd",
    dataDir: "development-data",
    projectsRoot: "development-projects",
    allowedOrigins: ["https://development.example.ts.net"],
    accounts: [
      { id: "account-a", label: "A", codexHome: "home-a" },
      { id: "history", label: "History", codexHome: "home-history", historyOnly: true }
    ],
    workspaces: [{ id: "project", label: "Project", path: "project-path" }]
  };

  const merged = mergeWindowsConfiguration(installed, development);

  assert.deepEqual(merged.deviceAuthentication, { required: true });
  assert.equal(merged.codexCliPath, "installed-codex.cmd");
  assert.equal(merged.dataDir, "installed-data");
  assert.deepEqual(merged.futureSetting, { preserve: true });
  assert.equal(merged.projectsRoot, "development-projects");
  assert.deepEqual(merged.accounts, development.accounts);
  assert.deepEqual(merged.workspaces, development.workspaces);
  assert.deepEqual(merged.allowedOrigins, [
    "https://installed.example.ts.net",
    "https://development.example.ts.net"
  ]);
  assert.notEqual(merged.accounts, development.accounts);
});

test("Windows config sync rejects duplicate account and workspace ids", () => {
  assert.throws(() => mergeWindowsConfiguration(
    { accounts: [], workspaces: [] },
    { accounts: [{ id: "same" }, { id: "same" }], workspaces: [] }
  ), /configuration_duplicate_id/);
  assert.throws(() => mergeWindowsConfiguration(
    { accounts: [], workspaces: [] },
    { accounts: [], workspaces: [{ id: "same" }, { id: "same" }] }
  ), /configuration_duplicate_id/);
});

test("Windows installer build synchronizes the local installed configuration first", async () => {
  const manifest = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8"));
  assert.match(manifest.scripts["build:windows-installer"], /^node tools\/sync-windows-config\.mjs && /);
});
