import { afterEach, describe, expect, it, vi } from "vitest";
import { consumeStartupToast } from "../src/dimsdk/pages/utils/startup-toast.ts";

function createStore(env: Record<string, string | undefined>) {
  const shownUpgrades: string[] = [];
  const state = {
    context: {
      env: { ...env },
    },
    ui: {
      onboarding: {
        lastSeenVersion: "",
      },
      upgradeNotification: {
        visible: false,
        message: "",
      },
    },
  };

  return {
    state,
    shownUpgrades,
    store: {
      state,
      setEnvVar(key: string, value: string | undefined) {
        state.context.env[key] = value;
      },
      showUpgradeNotification(text: string) {
        shownUpgrades.push(text);
      },
    },
  };
}

afterEach(() => {
  vi.unstubAllGlobals();
});

describe("startup toast", () => {
  it("consumes one-shot startup toast and clears process env in node mode", () => {
    vi.stubGlobal("process", {
      env: {
        DIMCODE_TEST: "1",
        DIMCODE_STARTUP_TOAST: "hello from process",
      },
    });

    const shownToasts: string[] = [];
    const { state, store } = createStore({
      DIMCODE_STARTUP_TOAST: "hello from env",
    });

    consumeStartupToast({
      store: store as Parameters<typeof consumeStartupToast>[0]["store"],
      nodeLike: true,
      showToast(text) {
        shownToasts.push(text);
      },
    });

    expect(shownToasts).toEqual(["hello from env"]);
    expect(state.context.env.DIMCODE_STARTUP_TOAST).toBeUndefined();
    expect((globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env?.DIMCODE_STARTUP_TOAST).toBeUndefined();
  });

  it("shows onboarding upgrade toast once per unseen runtime version", () => {
    vi.stubGlobal("process", {
      env: {},
    });

    const shownToasts: string[] = [];
    const { state, shownUpgrades, store } = createStore({
      DIMCODE_VERSION: "1.2.3",
    });

    consumeStartupToast({
      store: store as Parameters<typeof consumeStartupToast>[0]["store"],
      nodeLike: false,
      showToast(text) {
        shownToasts.push(text);
      },
    });
    consumeStartupToast({
      store: store as Parameters<typeof consumeStartupToast>[0]["store"],
      nodeLike: false,
      showToast(text) {
        shownToasts.push(text);
      },
    });

    expect(shownToasts).toEqual([]);
    expect(shownUpgrades).toHaveLength(1);
    expect(shownUpgrades[0]).toBeTruthy();
    expect(state.ui.onboarding.lastSeenVersion).toBe("1.2.3");
  });
});
