import ls from "localstorage-slim";
import { Thumbmark } from "@thumbmarkjs/thumbmarkjs";
import { useGraphQlOperation } from "./graphqlOperation.js";
import { useHostAgent } from "./hostAgent.js";
function isPlainObject(v) {
  return v !== null && typeof v === "object" && !Array.isArray(v);
}
function readConfig(storageKey) {
  try {
    const v = ls.get(storageKey);
    if (!v || !isPlainObject(v)) return null;
    return v;
  } catch {
    return null;
  }
}
function writeConfig(storageKey, cfg) {
  ls.set(storageKey, cfg);
}
function clearConfig(storageKey) {
  ls.remove(storageKey);
}
export function createClientConfigService(opts = {}) {
  const storageKey = opts.storageKey ?? "client_config";
  const thumbmarkInstance = new Thumbmark();
  return {
    get() {
      return readConfig(storageKey);
    },
    set(cfg) {
      if (!isPlainObject(cfg)) {
        throw new Error("ClientConfig must be a JSON-serializable object.");
      }
      JSON.stringify(cfg);
      writeConfig(storageKey, cfg);
    },
    clear() {
      clearConfig(storageKey);
    },
    async load() {
      try {
        const cfg = await this.fetchFromGraphql();
        this.set(cfg);
        return cfg;
      } catch {
        return this.get();
      }
    },
    async fetchFromGraphql() {
      const thumbmark = await thumbmarkInstance.get();
      let computerName = thumbmark.thumbmark;
      try {
        const machineInfo = await useHostAgent().getMachineInfo();
        if (machineInfo?.computerName) {
          computerName = machineInfo.computerName;
        }
      } catch (err) {
        console.warn("[client-config] getMachineInfo() failed, fallback to fingerprint:", err);
      }
      try {
        const result = await useGraphQlOperation(
          "Query",
          "clientConfigByComputerNameAndFingerprint",
          ["*"],
          {
            computerName,
            fingerprint: thumbmark.thumbmark
          },
          false
        );
        if (!result || !result.configuration) return {};
        return result.configuration;
      } catch (err) {
        console.warn("[client-config] fetching config failed:", err);
        return {};
      }
    }
  };
}
