import { describe, it, expect, vi, beforeEach } from "vitest";
import { setActivePinia, createPinia } from "pinia";
import { useScriptsStore } from "../scripts.js";

vi.mock("../../api/modules/scripts.js", () => ({
  scriptsApi: {
    actionsList: vi.fn(),
    regularList: vi.fn(),
    scopesList: vi.fn(),
    runAction: vi.fn(),
    setRegularState: vi.fn(),
    setScopeState: vi.fn(),
  },
}));

import { scriptsApi } from "../../api/modules/scripts.js";

describe("useScriptsStore regular and scopes", () => {
  beforeEach(() => {
    setActivePinia(createPinia());
    vi.clearAllMocks();
  });

  describe("loadRegular", () => {
    it("sets regular scripts on success", async () => {
      scriptsApi.regularList.mockResolvedValue({
        ok: true,
        data: { data: { scripts: [{ alias: "check", name: "Check", state: "enabled" }] } },
      });

      const store = useScriptsStore();
      await store.loadRegular();

      expect(store.regular.length).toBe(1);
      expect(store.regular[0].alias).toBe("check");
      expect(store.isLoadingRegular).toBe(false);
    });

    it("ignores timeout abort", async () => {
      scriptsApi.regularList.mockResolvedValue({
        ok: false,
        error: { type: "timeout" },
      });

      const store = useScriptsStore();
      await store.loadRegular();

      expect(store.errorRegular).toBeNull();
      expect(store.isLoadingRegular).toBe(false);
    });
  });

  describe("loadScopes", () => {
    it("sets scopes on success", async () => {
      scriptsApi.scopesList.mockResolvedValue({
        ok: true,
        data: { data: { scopes: [{ name: "HubScope", filename: "HubScope.php", state: "enabled" }] } },
      });

      const store = useScriptsStore();
      await store.loadScopes();

      expect(store.scopes.length).toBe(1);
      expect(store.scopes[0].name).toBe("HubScope");
      expect(store.isLoadingScopes).toBe(false);
    });

    it("ignores timeout abort", async () => {
      scriptsApi.scopesList.mockResolvedValue({
        ok: false,
        error: { type: "timeout" },
      });

      const store = useScriptsStore();
      await store.loadScopes();

      expect(store.errorScopes).toBeNull();
      expect(store.isLoadingScopes).toBe(false);
    });
  });
});
