function clone(value) {
  return value === undefined ? undefined : structuredClone(value);
}

function validatedList(config, key) {
  const list = config?.[key];
  if (!Array.isArray(list)) throw new Error("configuration_invalid");
  const ids = new Set();
  for (const item of list) {
    if (!item || typeof item !== "object" || typeof item.id !== "string" || !item.id) {
      throw new Error("configuration_invalid");
    }
    if (ids.has(item.id)) throw new Error("configuration_duplicate_id");
    ids.add(item.id);
  }
  return list;
}

export function mergeWindowsConfiguration(installed, development) {
  const accounts = validatedList(development, "accounts");
  const workspaces = validatedList(development, "workspaces");
  validatedList(installed, "accounts");
  validatedList(installed, "workspaces");

  const merged = clone(installed);
  merged.accounts = clone(accounts);
  merged.workspaces = clone(workspaces);
  if (typeof development.projectsRoot === "string" && development.projectsRoot) {
    merged.projectsRoot = development.projectsRoot;
  }

  const origins = new Set();
  for (const origin of [...(installed.allowedOrigins ?? []), ...(development.allowedOrigins ?? [])]) {
    if (typeof origin === "string" && origin) origins.add(origin);
  }
  if (origins.size > 0) merged.allowedOrigins = [...origins];
  return merged;
}
