import type { FeedFilters } from "./api";

// Single source of truth for React Query keys. Every key root lives here exactly once, so a typo
// at one of the ~200 call sites can no longer mint an orphan key that silently never invalidates
// (the R7 driver: `["feed"]` was hand-written in 15+ files). CONTRACT: each function returns the
// SAME array shape the call sites used before, so TanStack's partial (prefix) matching is
// unchanged — `qk.feed()` (`["feed"]`) still invalidates `qk.feed(filters)` (`["feed", filters]`).
// Deliberately NOT bundling co-invalidations into helpers here: the clusters differ per call site
// (some invalidate `feed` alone, others `feed` + `feed-count`), so collapsing them would change
// which queries refetch. Grouped invalidation stays opt-in per domain (see `invalidateDownloads`).
// Extended per domain as R7 S2 migrates each area (S2a: feed/channels/playlists + shared roots).
export const qk = {
  // --- shared roots (invalidated from more than one domain) ---
  me: () => ["me"] as const,
  myStatus: () => ["my-status"] as const,
  tags: () => ["tags"] as const,

  // --- feed / video ---
  feed: (filters?: FeedFilters) => (filters ? (["feed", filters] as const) : (["feed"] as const)),
  feedCount: (filters?: FeedFilters) =>
    filters ? (["feed-count", filters] as const) : (["feed-count"] as const),
  facets: (filters?: FeedFilters) =>
    filters ? (["facets", filters] as const) : (["facets"] as const),
  // `q`/`id` accept null (not just undefined) because the call sites key on nullable state
  // (`selectedId`, the search string): a NULL is a real key segment and must be preserved
  // (`["playlist", null]`), while a genuinely absent arg is the bare prefix key. The guard is
  // `!== undefined`, so only the no-arg call collapses to the prefix.
  ytSearch: (q?: string | null, count?: number) =>
    q !== undefined ? (["yt-search", q, count] as const) : (["yt-search"] as const),
  videoDetail: (id: string) => ["video-detail", id] as const,

  // --- channels ---
  channels: () => ["channels"] as const,
  channel: (id: string) => ["channel", id] as const,
  discoveredChannels: () => ["discovered-channels"] as const,
  blockedChannels: () => ["blocked-channels"] as const,

  // --- playlists ---
  playlists: () => ["playlists"] as const,
  playlist: (id?: number | null) =>
    id !== undefined ? (["playlist", id] as const) : (["playlist"] as const),
  playlistMembership: (videoId: string) => ["playlist-membership", videoId] as const,
  savedViews: () => ["saved-views"] as const,
};
