import { SSE_EVENT_TYPES } from "@capakraken/shared";
import { describe, expect, it } from "vitest";
import {
  getTimelineSseInvalidationKeys,
  getTimelineSseResyncKeys,
  parseTimelineSseEvent,
} from "./timelineSsePolicy.js";

describe("timelineSsePolicy", () => {
  it("returns null for malformed event payloads", () => {
    expect(parseTimelineSseEvent("{not-json")).toBeNull();
    expect(parseTimelineSseEvent(JSON.stringify({ nope: "missing-type" }))).toBeNull();
    expect(parseTimelineSseEvent(JSON.stringify({ type: 42 }))).toBeNull();
  });

  it("does not invalidate queries for unknown event types", () => {
    expect(getTimelineSseInvalidationKeys("timeline.unknown")).toEqual([]);
  });

  it("maps allocation and vacation updates to planning query invalidations", () => {
    expect(getTimelineSseInvalidationKeys(SSE_EVENT_TYPES.ALLOCATION_UPDATED)).toEqual([
      [["timeline", "getEntries"]],
      [["timeline", "getEntriesView"]],
      [["timeline", "getMyEntriesView"]],
      [["timeline", "getHolidayOverlays"]],
      [["timeline", "getMyHolidayOverlays"]],
      [["vacation", "list"]],
      [["allocation", "list"]],
    ]);
  });

  it("maps task updates to task and notification invalidations", () => {
    expect(getTimelineSseInvalidationKeys(SSE_EVENT_TYPES.TASK_STATUS_CHANGED)).toEqual([
      [["notification", "listTasks"]],
      [["notification", "taskCounts"]],
      [["notification", "list"]],
      [["notification", "unreadCount"]],
    ]);
  });

  it("returns the full resync invalidation set for reconnect catch-up", () => {
    expect(getTimelineSseResyncKeys()).toEqual([
      [["timeline", "getEntries"]],
      [["timeline", "getEntriesView"]],
      [["timeline", "getMyEntriesView"]],
      [["timeline", "getHolidayOverlays"]],
      [["timeline", "getMyHolidayOverlays"]],
      [["vacation", "list"]],
      [["allocation", "list"]],
      [["project", "list"]],
      [["timeline", "getBudgetStatus"]],
      [["notification", "listTasks"]],
      [["notification", "taskCounts"]],
      [["notification", "list"]],
      [["notification", "unreadCount"]],
      [["notification", "listReminders"]],
    ]);
  });
});
