import { describe, expect, it, beforeEach, vi } from "vitest";
import { createAnalytics } from "./facade.js";
import { getRecordedEvents, resetEvents } from "./sink.js";
import type { Logger } from "@/observability/logger/types";

function mockLogger(): Logger {
  return {
    debug: vi.fn(),
    info: vi.fn(),
    warn: vi.fn(),
    error: vi.fn(),
    child: vi.fn(() => mockLogger()),
  };
}

describe("createAnalytics", () => {
  beforeEach(() => {
    resetEvents();
  });

  it("fans out track() to all 4 enabled adapters", () => {
    const analytics = createAnalytics({
      enabled: { metrica: true, ctm: true, variocube: true, dynatrace: true },
      consent: { analytics: true, telemetry: true },
      logger: mockLogger(),
    });

    analytics.track("test.event", { key: "value" });

    const events = getRecordedEvents();
    expect(events).toHaveLength(4);

    const providers = events.map((e) => e.provider).sort();
    expect(providers).toEqual(["ctm", "dynatrace", "metrica", "variocube"]);

    for (const event of events) {
      expect(event.kind).toBe("track");
      expect(event.name).toBe("test.event");
      expect(event.props).toEqual({ key: "value" });
    }
  });

  it("fans out page() to all 4 enabled adapters", () => {
    const analytics = createAnalytics({
      enabled: { metrica: true, ctm: true, variocube: true, dynatrace: true },
      consent: { analytics: true, telemetry: true },
      logger: mockLogger(),
    });

    analytics.page("/ru/online-board");

    const events = getRecordedEvents();
    expect(events).toHaveLength(4);

    for (const event of events) {
      expect(event.kind).toBe("page");
      expect(event.name).toBe("/ru/online-board");
    }
  });

  it("consent.analytics = false short-circuits before any adapter is invoked", () => {
    const analytics = createAnalytics({
      enabled: { metrica: true, ctm: true, variocube: true, dynatrace: true },
      consent: { analytics: false, telemetry: true },
      logger: mockLogger(),
    });

    analytics.track("should.not.emit");
    analytics.page("/should/not/emit");

    expect(getRecordedEvents()).toHaveLength(0);
  });

  it("disabled adapter is not invoked", () => {
    const analytics = createAnalytics({
      enabled: { metrica: true, ctm: false, variocube: false, dynatrace: true },
      consent: { analytics: true, telemetry: true },
      logger: mockLogger(),
    });

    analytics.track("partial.event");

    const events = getRecordedEvents();
    expect(events).toHaveLength(2);

    const providers = events.map((e) => e.provider).sort();
    expect(providers).toEqual(["dynatrace", "metrica"]);
  });
});
