import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { fetchUsageSummary } from "./telemetry";

vi.mock("./client", () => ({
  apiGet: vi.fn(),
}));

const { apiGet } = await import("./client");

describe("Telemetry API Client", (): void => {
  beforeEach((): void => {
    vi.clearAllMocks();
    vi.useFakeTimers();
    vi.setSystemTime(new Date("2026-03-02T12:00:00Z"));
  });

  afterEach((): void => {
    vi.useRealTimers();
  });

  it("fetches usage summary from llm usage analytics endpoint", async (): Promise<void> => {
    vi.mocked(apiGet).mockResolvedValueOnce({
      data: {
        totalCalls: 47,
        totalPromptTokens: 120000,
        totalCompletionTokens: 125800,
        totalTokens: 245800,
        totalCostCents: 342,
        averageDurationMs: 3200,
        byProvider: [],
        byModel: [],
        byTaskType: [],
      },
    });

    const result = await fetchUsageSummary("30d");

    const calledEndpoint = vi.mocked(apiGet).mock.calls[0]?.[0];
    expect(calledEndpoint).toMatch(/^\/api\/llm-usage\/analytics\?/);

    const queryString = calledEndpoint?.split("?")[1] ?? "";
    const params = new URLSearchParams(queryString);
    expect(params.get("startDate")).toBeTruthy();
    expect(params.get("endDate")).toBeTruthy();

    expect(result).toEqual({
      totalTokens: 245800,
      totalCost: 3.42,
      taskCount: 47,
      avgQualityGatePassRate: 0,
    });
  });
});
