// The Lucia project.
// Copyright 2026-2026 DSP, inc.  All rights reserved.
// Authors:
//   imacat.yang@dsp.im (imacat), 2026/03/05

import { describe, it, expect, beforeEach, vi } from "vitest";
import { setActivePinia, createPinia } from "pinia";
import { http, HttpResponse } from "msw";
import { server } from "@/mocks/node.js";
import { findRequest, captureRequest } from "@/mocks/request-log.js";

vi.mock("@/module/apiError.js", () => ({
  default: vi.fn(),
}));

import { useCompareStore } from "@/stores/compare";

describe("compareStore", () => {
  let store;

  beforeEach(() => {
    setActivePinia(createPinia());
    store = useCompareStore();
    document.cookie = "luciaToken=fake-test-token";
  });

  it("has correct default state", () => {
    expect(store.allCompareDashboardData).toBeNull();
  });

  it("compareDashboardData getter returns state", () => {
    store.allCompareDashboardData = { time: {} };
    expect(store.compareDashboardData).toEqual({ time: {} });
  });

  describe("getCompare", () => {
    it("fetches compare data with encoded params", async () => {
      const params = [{ type: "log", id: 1 }];
      const mockData = { time: {}, freq: {} };
      server.use(
        http.get("/api/compare", ({ request }) => {
          captureRequest("GET", new URL(request.url).pathname
            + new URL(request.url).search);
          return HttpResponse.json(mockData);
        }),
      );

      await store.getCompare(params);

      const encoded = encodeURIComponent(JSON.stringify(params));
      const reqs = findRequest("GET", `/api/compare?datasets=${encoded}`);
      expect(reqs).toHaveLength(1);
      expect(store.allCompareDashboardData).toEqual(mockData);
    });

    it("does not throw on API failure", async () => {
      server.use(
        http.get("/api/compare", () => new HttpResponse(null, { status: 500 })),
      );

      await expect(store.getCompare([])).resolves.not.toThrow();
    });
  });

  describe("getStateData", () => {
    it("fetches log discover stats", async () => {
      server.use(
        http.get("/api/logs/:id/discover", ({ request }) => {
          captureRequest("GET", new URL(request.url).pathname);
          return HttpResponse.json({ stats: { cases: 100 } });
        }),
      );

      const result = await store.getStateData("log", 1);

      const reqs = findRequest("GET", "/api/logs/1/discover");
      expect(reqs).toHaveLength(1);
      expect(result).toEqual({ cases: 100 });
    });

    it("fetches filter discover stats", async () => {
      server.use(
        http.get("/api/filters/:id/discover", ({ request }) => {
          captureRequest("GET", new URL(request.url).pathname);
          return HttpResponse.json({ stats: { cases: 50 } });
        }),
      );

      const result = await store.getStateData("filter", 3);

      const reqs = findRequest("GET", "/api/filters/3/discover");
      expect(reqs).toHaveLength(1);
      expect(result).toEqual({ cases: 50 });
    });

    it("returns null for unknown type", async () => {
      const result = await store.getStateData("unknown", 1);

      const reqs = findRequest("GET", /\/api\//);
      expect(reqs).toHaveLength(0);
      expect(result).toBeNull();
    });
  });

  describe("getFileName", () => {
    it("finds file name by id", async () => {
      server.use(
        http.get("/api/files", () =>
          HttpResponse.json([
            { id: 1, name: "file1.csv" },
            { id: 2, name: "file2.csv" },
          ]),
        ),
      );

      const result = await store.getFileName(1);

      expect(result).toBe("file1.csv");
    });

    it("returns empty string for non-existent id", async () => {
      server.use(
        http.get("/api/files", () =>
          HttpResponse.json([{ id: 1, name: "file1.csv" }]),
        ),
      );

      const result = await store.getFileName(99);

      expect(result).toBe("");
    });
  });
});
