import { SSE_EVENT_TYPES } from "@capakraken/shared";

export type TimelineQueryKey = readonly [readonly [string, string]];

const TIMELINE_ENTRY_KEYS: TimelineQueryKey[] = [
  [["timeline", "getEntries"]],
  [["timeline", "getEntriesView"]],
  [["timeline", "getMyEntriesView"]],
  [["timeline", "getHolidayOverlays"]],
  [["timeline", "getMyHolidayOverlays"]],
];

const NOTIFICATION_KEYS: TimelineQueryKey[] = [
  [["notification", "list"]],
  [["notification", "unreadCount"]],
];

const RESYNC_INVALIDATION_KEYS: TimelineQueryKey[] = [
  ...TIMELINE_ENTRY_KEYS,
  [["vacation", "list"]],
  [["allocation", "list"]],
  [["project", "list"]],
  [["timeline", "getBudgetStatus"]],
  [["notification", "listTasks"]],
  [["notification", "taskCounts"]],
  ...NOTIFICATION_KEYS,
  [["notification", "listReminders"]],
];

export function parseTimelineSseEvent(rawData: string): string | null {
  try {
    const data = JSON.parse(rawData) as { type?: unknown };
    return typeof data.type === "string" ? data.type : null;
  } catch {
    return null;
  }
}

export function getTimelineSseInvalidationKeys(eventType: string): TimelineQueryKey[] {
  switch (eventType) {
    case SSE_EVENT_TYPES.ALLOCATION_CREATED:
    case SSE_EVENT_TYPES.ALLOCATION_UPDATED:
    case SSE_EVENT_TYPES.ALLOCATION_DELETED:
    case SSE_EVENT_TYPES.VACATION_CREATED:
    case SSE_EVENT_TYPES.VACATION_UPDATED:
    case SSE_EVENT_TYPES.VACATION_DELETED:
      return [
        ...TIMELINE_ENTRY_KEYS,
        [["vacation", "list"]],
        [["allocation", "list"]],
      ];

    case SSE_EVENT_TYPES.PROJECT_SHIFTED:
      return [
        ...TIMELINE_ENTRY_KEYS,
        [["project", "list"]],
      ];

    case SSE_EVENT_TYPES.BUDGET_WARNING:
      return [[["timeline", "getBudgetStatus"]]];

    case SSE_EVENT_TYPES.NOTIFICATION_CREATED:
      return NOTIFICATION_KEYS;

    case SSE_EVENT_TYPES.TASK_ASSIGNED:
    case SSE_EVENT_TYPES.TASK_COMPLETED:
    case SSE_EVENT_TYPES.TASK_STATUS_CHANGED:
      return [
        [["notification", "listTasks"]],
        [["notification", "taskCounts"]],
        ...NOTIFICATION_KEYS,
      ];

    case SSE_EVENT_TYPES.REMINDER_DUE:
      return [
        ...NOTIFICATION_KEYS,
        [["notification", "listReminders"]],
      ];

    default:
      return [];
  }
}

export function getTimelineSseResyncKeys(): TimelineQueryKey[] {
  return RESYNC_INVALIDATION_KEYS;
}
