import { beforeEach, describe, expect, it, vi } from "vitest";
import { PrimariaBroker } from "../broker/primaria-broker";
import { PrimariaGlobalStateManager, createGlobalStateManager } from "./global-state";

describe("PrimariaGlobalStateManagerImpl", () => {
  let globalStateManager: PrimariaGlobalStateManager;
  let brokerMock: PrimariaBroker;

  beforeEach(() => {
    brokerMock = {
      publish: vi.fn(),
    } as any;
    globalStateManager = createGlobalStateManager(brokerMock);
  });

  it("should set and get data correctly", () => {
    globalStateManager.setData("key1", "value1");
    const result = globalStateManager.getData("key1");
    expect(result).toBe("value1");
  });

  it("should set data and publish an event", () => {
    const key = "key1";
    const value = "value1";
    globalStateManager.setData(key, value);

    expect(globalStateManager.getData(key)).toBe(value);
    expect(brokerMock.publish).toHaveBeenCalledWith("data_set", {
      key: key,
      value: value,
    });
  });

  it("should return undefined for non-existent key", () => {
    const result = globalStateManager.getData("nonExistentKey");
    expect(result).toBeUndefined();
  });

  it("should overwrite existing key with new value", () => {
    globalStateManager.setData("key1", "value1");
    globalStateManager.setData("key1", "newValue");
    const result = globalStateManager.getData("key1");
    expect(result).toBe("newValue");
  });

  it("should clear all data", () => {
    globalStateManager.setData("key1", "value1");
    globalStateManager.setData("key2", "value2");
    globalStateManager.clearData();
    expect(globalStateManager.getData("key1")).toBeUndefined();
    expect(globalStateManager.getData("key2")).toBeUndefined();
  });
});
