All files / src/common/utils cacheUtils.ts

22.01% Statements 216/981
55.55% Branches 35/63
27.02% Functions 10/37
22.01% Lines 216/981

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241              1x 1x               1x 22x 22x 22x   22x 22x 22x 22x 22x 22x 22x 22x 22x     22x                                                                                                                                                                                                                                                                                   22x                                                                                                                                                                                                                                                                                                 22x                                                                                                                                                           22x       14x 14x 14x 14x 14x 14x 14x 14x 14x 14x     14x 14x   14x 1x 1x 1x 1x 1x     13x 13x   13x 14x 14x 9x 9x 5x 5x 9x   14x 14x 2x 2x 1x 1x 2x   14x 14x       1x 1x 1x 1x 1x 1x 1x 1x   14x                       14x 1x 1x 1x 1x 1x 14x     11x 11x 11x 11x     11x 6x 6x 11x     11x   11x 11x 11x 11x 11x 11x 11x 11x 11x 14x 1x 1x 1x 1x 1x 1x 1x 1x 1x 14x     22x 5x   5x 5x 5x 5x 5x   3x 3x 3x 3x 3x   5x 5x 5x 5x 5x     1x 1x 1x 1x 1x 1x 1x 1x   5x 5x                     5x           5x 5x 5x 5x 5x 5x 5x 5x 5x                                 5x           5x                           5x                 5x 5x 5x 5x 5x 5x                     5x                 5x     1x 1x 1x 1x 1x   5x                 5x   5x                       5x 5x     22x                                                                                                                   22x 1x 1x 1x       1x 1x 1x                                               1x 1x     22x                                                                             22x                               22x                                                                                                                                                                                                                                                 22x                                                               22x             22x               22x                     22x                     22x                                                                         22x                       22x                                                                             22x                                       22x     1x   1x 22x 22x 22x 22x 22x 22x   1x 134x 59x 59x 75x 75x   1x 70x 70x     1x 20x 20x     1x                           1x         1x             1x         1x                     1x               1x                       1x 2x 2x 2x     1x               1x             1x        
import type {
  NewsletterWithRelations,
  PaginatedResponse,
  ReadingQueueItem,
  Tag,
} from '@common/types';
import { QueryClient } from '@tanstack/react-query';
import { logger } from './logger';
import { queryKeyFactory } from './queryKeyFactory';
 
interface CacheManagerConfig {
  enableOptimisticUpdates?: boolean;
  enableCrossFeatureSync?: boolean;
  enablePerformanceLogging?: boolean;
}
 
export class SimpleCacheManager {
  public queryClient: QueryClient;
  private config: CacheManagerConfig;
  private log = logger;
 
  constructor(queryClient: QueryClient, config: CacheManagerConfig = {}) {
    this.queryClient = queryClient;
    this.config = {
      enableOptimisticUpdates: true,
      enableCrossFeatureSync: true,
      enablePerformanceLogging: false,
      ...config,
    };
  }
 
  // Update newsletter in cache
  updateNewsletterInCache(update: { id: string; updates: Partial<NewsletterWithRelations> }): void {
    try {
      this.log.debug('Updating newsletter in cache', {
        action: 'update_newsletter_cache_start',
        metadata: {
          newsletterId: update.id,
          updates: update.updates,
          updateFields: Object.keys(update.updates),
        },
      });
 
      // Update in all newsletter list queries using predicate
      this.queryClient.setQueriesData<PaginatedResponse<NewsletterWithRelations>>(
        {
          predicate: (query) => {
            const key = query.queryKey;
            return (
              Array.isArray(key) &&
              key[0] === 'newsletters' &&
              key[1] === 'list' &&
              key[2] !== 'infinite'
            );
          },
        },
        (oldData: PaginatedResponse<NewsletterWithRelations> | undefined) => {
          if (!oldData || !oldData.data || !Array.isArray(oldData.data)) return oldData;
          return {
            ...oldData,
            data: oldData.data.map((newsletter: NewsletterWithRelations) =>
              newsletter.id === update.id ? { ...newsletter, ...update.updates } : newsletter
            ),
          };
        }
      );
 
      // Update in infinite queries (for Inbox view) using predicate
      this.queryClient.setQueriesData<{ pages: PaginatedResponse<NewsletterWithRelations>[] }>(
        {
          predicate: (query) => {
            const key = query.queryKey;
            return (
              Array.isArray(key) &&
              key[0] === 'newsletters' &&
              key[1] === 'infinite'
            );
          },
        },
        (oldData) => {
          if (!oldData || !oldData.pages) return oldData;
 
          let foundAndUpdated = false;
          const updatedData = {
            ...oldData,
            pages: oldData.pages.map((page) => ({
              ...page,
              data: page.data.map((newsletter: NewsletterWithRelations) => {
                if (newsletter.id === update.id) {
                  foundAndUpdated = true;
                  this.log.debug('Found newsletter in infinite query page', {
                    action: 'update_infinite_query',
                    metadata: {
                      newsletterId: update.id,
                      oldValues: {
                        is_read: newsletter.is_read,
                        is_liked: newsletter.is_liked,
                        is_archived: newsletter.is_archived,
                      },
                      newValues: update.updates,
                    },
                  });
                  return { ...newsletter, ...update.updates };
                }
                return newsletter;
              }),
            })),
          };
 
          if (!foundAndUpdated) {
            this.log.warn('Newsletter not found in infinite query', {
              action: 'update_infinite_query_not_found',
              metadata: { newsletterId: update.id },
            });
          }
 
          return updatedData;
        }
      );
 
      // Update individual newsletter query if it exists
      const detailQueryKey = queryKeyFactory.newsletters.detail(update.id);
      this.queryClient.setQueryData<NewsletterWithRelations | undefined>(
        detailQueryKey,
        (oldData) => {
          if (!oldData) return oldData;
          return { ...oldData, ...update.updates };
        }
      );
 
      // Cross-feature sync: Update newsletter in reading queue if it exists there
      if (this.config.enableCrossFeatureSync) {
        this.queryClient.setQueriesData<ReadingQueueItem[] | undefined>(
          { queryKey: queryKeyFactory.queue.all() },
          (oldData) => {
            if (!Array.isArray(oldData)) return oldData;
            return oldData.map((queueItem) =>
              queueItem.newsletter?.id === update.id
                ? {
                  ...queueItem,
                  newsletter: { ...queueItem.newsletter, ...update.updates },
                }
                : queueItem
            );
          }
        );
      }
 
      if (this.config.enablePerformanceLogging) {
        this.log.debug('Newsletter cache updated', {
          action: 'update_newsletter_cache',
          metadata: {
            newsletterId: update.id,
            updatedFields: Object.keys(update.updates),
          },
        });
      }
    } catch (error) {
      this.log.error(
        'Failed to update newsletter in cache',
        {
          action: 'update_newsletter_cache_error',
          metadata: { newsletterId: update.id },
        },
        error instanceof Error ? error : new Error(String(error))
      );
    }
  }
 
  // Batch update newsletters in cache
  batchUpdateNewsletters(
    updates: Array<{ id: string; updates: Partial<NewsletterWithRelations> }>
  ): void {
    try {
      this.log.debug('Starting batch newsletter update', {
        action: 'batch_update_start',
        metadata: {
          count: updates.length,
          newsletterIds: updates.map((u) => u.id),
          updateFields: updates.length > 0 ? Object.keys(updates[0].updates) : [],
        },
      });
 
      // Create a map for efficient lookup
      const updateMap = new Map(updates.map((u) => [u.id, u.updates]));
 
      // Update in all newsletter list queries using predicate
      this.queryClient.setQueriesData<PaginatedResponse<NewsletterWithRelations>>(
        {
          predicate: (query) => {
            const key = query.queryKey;
            return (
              Array.isArray(key) &&
              key[0] === 'newsletters' &&
              key[1] === 'list' &&
              key[2] !== 'infinite'
            );
          },
        },
        (oldData) => {
          if (!oldData || !oldData.data || !Array.isArray(oldData.data)) return oldData;
          return {
            ...oldData,
            data: oldData.data.map((newsletter: NewsletterWithRelations) => {
              const updates = updateMap.get(newsletter.id);
              return updates ? { ...newsletter, ...updates } : newsletter;
            }),
          };
        }
      );
 
      // Update in infinite queries (for Inbox view) using predicate
      this.queryClient.setQueriesData<{ pages: PaginatedResponse<NewsletterWithRelations>[] }>(
        {
          predicate: (query) => {
            const key = query.queryKey;
            return (
              Array.isArray(key) &&
              key[0] === 'newsletters' &&
              key[1] === 'infinite'
            );
          },
        },
        (oldData) => {
          if (!oldData || !oldData.pages) return oldData;
 
          let updateCount = 0;
          const updatedData = {
            ...oldData,
            pages: oldData.pages.map((page) => ({
              ...page,
              data: page.data.map((newsletter: NewsletterWithRelations) => {
                const updates = updateMap.get(newsletter.id);
                if (updates) {
                  updateCount++;
                }
                return updates ? { ...newsletter, ...updates } : newsletter;
              }),
            })),
          };
 
          this.log.debug('Batch update in infinite queries', {
            action: 'batch_update_infinite',
            metadata: {
              totalPages: oldData.pages.length,
              updatedCount: updateCount,
              requestedCount: updates.length,
            },
          });
 
          return updatedData;
        }
      );
 
      // Update individual newsletter queries
      updates.forEach(({ id, updates }) => {
        const detailQueryKey = queryKeyFactory.newsletters.detail(id);
        this.queryClient.setQueryData<NewsletterWithRelations | undefined>(
          detailQueryKey,
          (oldData) => {
            if (!oldData) return oldData;
            return { ...oldData, ...updates };
          }
        );
      });
 
      // Cross-feature sync: Update newsletters in reading queue
      if (this.config.enableCrossFeatureSync) {
        this.queryClient.setQueriesData<ReadingQueueItem[] | undefined>(
          {
            predicate: (query) => {
              const key = query.queryKey;
              return Array.isArray(key) && key[0] === 'queue';
            },
          },
          (oldData) => {
            if (!Array.isArray(oldData)) return oldData;
            return oldData.map((queueItem) => {
              if (queueItem.newsletter) {
                const updates = updateMap.get(queueItem.newsletter.id);
                if (updates) {
                  return {
                    ...queueItem,
                    newsletter: { ...queueItem.newsletter, ...updates },
                  };
                }
              }
              return queueItem;
            });
          }
        );
      }
 
      if (this.config.enablePerformanceLogging) {
        this.log.debug('Batch newsletter cache updated', {
          action: 'batch_update_newsletter_cache',
          metadata: {
            count: updates.length,
            newsletterIds: updates.map((u) => u.id),
          },
        });
      }
    } catch (error) {
      this.log.error(
        'Failed to batch update newsletters in cache',
        {
          action: 'batch_update_newsletter_cache_error',
          metadata: { updateCount: updates.length },
        },
        error instanceof Error ? error : new Error(String(error))
      );
    }
  }
 
  // Reading queue operations
  updateReadingQueueInCache(operation: {
    type: 'add' | 'remove' | 'reorder' | 'updateTags' | 'revert';
    newsletterId?: string;
    queueItemId?: string;
    updates?: { id: string; position: number }[];
    tagIds?: string[];
    queueItems?: ReadingQueueItem[];
    userId: string;
  }): void {
    const queueQueryKey = queryKeyFactory.queue.list(operation.userId);
 
    switch (operation.type) {
      case 'add':
        // For add operations, we'll just invalidate to refetch
        // since we need full newsletter data
        this.queryClient.invalidateQueries({ queryKey: queueQueryKey });
        break;
 
      case 'remove':
        if (operation.queueItemId) {
          this.queryClient.setQueryData<ReadingQueueItem[]>(queueQueryKey, (oldData = []) =>
            oldData.filter((item) => item.id !== operation.queueItemId)
          );
        }
        break;
 
      case 'reorder':
        if (operation.updates) {
          this.queryClient.setQueryData<ReadingQueueItem[]>(queueQueryKey, (oldData = []) => {
            const reorderedData = [...oldData];
            operation.updates!.forEach(({ id, position }) => {
              const itemIndex = reorderedData.findIndex((item) => item.id === id);
              if (itemIndex !== -1) {
                reorderedData[itemIndex] = {
                  ...reorderedData[itemIndex],
                  position,
                };
              }
            });
            return reorderedData.sort((a, b) => a.position - b.position);
          });
        }
        break;
 
      case 'updateTags':
        if (operation.newsletterId && operation.tagIds) {
          this.queryClient.setQueryData<ReadingQueueItem[]>(queueQueryKey, (oldData = []) =>
            oldData.map((item) =>
              item.newsletter_id === operation.newsletterId
                ? {
                  ...item,
                  newsletter: {
                    ...item.newsletter,
                    tags: operation.tagIds!.map((tagId) => ({
                      id: tagId,
                      name: '',
                      color: '#808080',
                      user_id: operation.userId,
                      created_at: new Date().toISOString(),
                      updated_at: new Date().toISOString(),
                    })),
                  },
                }
                : item
            )
          );
        }
        break;
 
      case 'revert':
        if (operation.queueItems) {
          this.queryClient.setQueryData<ReadingQueueItem[]>(queueQueryKey, operation.queueItems);
        }
        break;
    }
  }
 
  // Update unread count optimistically without database hit
  updateUnreadCountOptimistically(operation: {
    type: 'mark-read' | 'mark-unread' | 'bulk-mark-read' | 'bulk-mark-unread' | 'archive' | 'unarchive' | 'delete';
    newsletterIds: string[];
    sourceId?: string;
  }): void {
    try {
      this.log.debug('Updating unread count optimistically', {
        action: 'update_unread_count_optimistic',
        metadata: {
          operation: operation.type,
          newsletterIds: operation.newsletterIds,
          sourceId: operation.sourceId,
        },
      });
 
      // Get current unread count data
      const unreadCountQueryKey = ['unreadCount', 'all'];
      const currentData = this.queryClient.getQueryData<{ total: number; bySource: Record<string, number> }>(unreadCountQueryKey);
 
      if (!currentData) {
        this.log.debug('No current unread count data found, skipping optimistic update', {
          action: 'update_unread_count_no_data',
        });
        return;
      }
 
      // Calculate the change based on operation type
      let totalChange = 0;
      const sourceChanges: Record<string, number> = {};
 
      switch (operation.type) {
        case 'mark-read':
        case 'bulk-mark-read':
          totalChange = -operation.newsletterIds.length;
          if (operation.sourceId) {
            sourceChanges[operation.sourceId] = -operation.newsletterIds.length;
          }
          break;
 
        case 'mark-unread':
        case 'bulk-mark-unread':
          totalChange = operation.newsletterIds.length;
          if (operation.sourceId) {
            sourceChanges[operation.sourceId] = operation.newsletterIds.length;
          }
          break;
 
        case 'archive':
        case 'delete':
          // For archive/delete, we need to check if the newsletters were unread
          // This is more complex and might require fetching newsletter details
          // For now, we'll invalidate the cache for these operations
          this.log.debug('Archive/delete operation detected, invalidating unread count', {
            action: 'update_unread_count_archive_delete',
          });
          this.queryClient.invalidateQueries({
            queryKey: ['unreadCount'],
            refetchType: 'active',
          });
          return;
 
        case 'unarchive':
          // For unarchive, we need to check if the newsletters should be unread
          // This is also complex, so we'll invalidate
          this.log.debug('Unarchive operation detected, invalidating unread count', {
            action: 'update_unread_count_unarchive',
          });
          this.queryClient.invalidateQueries({
            queryKey: ['unreadCount'],
            refetchType: 'active',
          });
          return;
 
        default:
          this.log.warn('Unknown operation type for unread count update', {
            action: 'update_unread_count_unknown_operation',
            metadata: { operation: operation.type },
          });
          return;
      }
 
      // Update the cache optimistically
      const updatedData = {
        total: Math.max(0, currentData.total + totalChange),
        bySource: { ...currentData.bySource },
      };
 
      // Update source-specific counts
      Object.entries(sourceChanges).forEach(([sourceId, change]) => {
        const currentSourceCount = updatedData.bySource[sourceId] || 0;
        updatedData.bySource[sourceId] = Math.max(0, currentSourceCount + change);
      });
 
      // Set the updated data in cache
      this.queryClient.setQueryData(unreadCountQueryKey, updatedData);
 
      this.log.debug('Unread count updated optimistically', {
        action: 'update_unread_count_success',
        metadata: {
          previousTotal: currentData.total,
          newTotal: updatedData.total,
          totalChange,
          sourceChanges,
        },
      });
    } catch (error) {
      this.log.error(
        'Failed to update unread count optimistically',
        {
          action: 'update_unread_count_optimistic_error',
          metadata: { operation: operation.type, newsletterIds: operation.newsletterIds },
        },
        error instanceof Error ? error : new Error(String(error))
      );
    }
  }
 
  // Smart invalidation with operation types
  invalidateRelatedQueries(newsletterIds: string[], operationType: string): void {
    const invalidationPromises: Promise<void>[] = [];
 
    switch (operationType) {
      case 'mark-read':
      case 'mark-unread':
      case 'bulk-mark-read':
      case 'bulk-mark-unread':
        // Use optimistic updates for unread count instead of invalidation
        this.updateUnreadCountOptimistically({
          type: operationType as 'mark-read' | 'mark-unread' | 'bulk-mark-read' | 'bulk-mark-unread',
          newsletterIds,
        });
        break;
 
      case 'toggle-archive':
      case 'archive':
      case 'unarchive':
      case 'bulk-archive':
      case 'bulk-unarchive':
        // For archive operations, we need to remove items from filtered views
        // and invalidate unread counts
        this.handleArchiveInvalidation(newsletterIds, operationType);
        invalidationPromises.push(
          this.queryClient.invalidateQueries({
            queryKey: ['unreadCount'],
            refetchType: 'active',
          })
        );
        break;
 
      case 'delete':
      case 'bulk-delete':
        // For delete operations, remove from all caches completely
        this.handleDeleteInvalidation(newsletterIds);
        invalidationPromises.push(
          this.queryClient.invalidateQueries({
            queryKey: ['unreadCount'],
            refetchType: 'active',
          })
        );
        break;
 
      case 'toggle-like':
        // For like operations, rely on optimistic updates only
        // No cache invalidation needed since optimistic updates handle the UI
        // This preserves filter state and prevents unnecessary refetches
        break;
 
      case 'toggle-queue':
      case 'queue-add':
      case 'queue-remove':
      case 'queue-reorder':
      case 'queue-clear':
      case 'queue-mark-read':
      case 'queue-mark-unread':
      case 'queue-update-tags':
      case 'queue-cleanup':
        // For all queue operations, invalidate reading queue and newsletter lists
        invalidationPromises.push(
          this.queryClient.invalidateQueries({
            queryKey: queryKeyFactory.queue.all(),
            refetchType: 'active',
          })
        );
        // Also refresh the newsletter lists to reflect any queue changes
        setTimeout(() => {
          this.queryClient.refetchQueries({
            queryKey: queryKeyFactory.newsletters.lists(),
            type: 'active',
          });
        }, 100);
        break;
 
      case 'toggle-like-error':
        // For like error cases, rely on rollback mechanism from optimistic updates
        // Avoid broad invalidation to preserve filter state
        // The mutation's onError callback handles rollbacks
        break;
 
      case 'toggle-queue-error':
        // For queue error cases, force refresh of both lists and queue
        invalidationPromises.push(
          this.queryClient.invalidateQueries({
            queryKey: queryKeyFactory.newsletters.lists(),
            refetchType: 'active',
          }),
          this.queryClient.invalidateQueries({
            queryKey: queryKeyFactory.queue.all(),
            refetchType: 'active',
          })
        );
        break;
 
      case 'tag-update':
        invalidationPromises.push(
          this.queryClient.invalidateQueries({
            queryKey: queryKeyFactory.newsletters.tags(),
            refetchType: 'active',
          })
        );
        break;
 
      case 'newsletter-sources':
      case 'source-update-optimistic':
      case 'source-update-error':
      case 'source-archive-optimistic':
      case 'source-unarchive-optimistic':
      case 'source-archive-error':
        invalidationPromises.push(
          this.queryClient.invalidateQueries({
            predicate: (query) => {
              return query.queryKey[0] === 'newsletterSources';
            },
            refetchType: 'active',
          })
        );
        break;
 
      case 'unread-count-change':
        invalidationPromises.push(
          this.queryClient.invalidateQueries({
            queryKey: ['unreadCount'],
            refetchType: 'active',
          })
        );
        break;
 
      case 'navigation':
        // For navigation operations, don't invalidate unread count
        // Let optimistic updates handle the changes
        this.log.debug('Navigation operation detected, skipping unread count invalidation', {
          action: 'navigation_skip_unread_invalidation',
          metadata: { newsletterIds },
        });
        break;
 
      default:
        // Fallback: invalidate general newsletter queries
        invalidationPromises.push(
          this.queryClient.invalidateQueries({
            queryKey: queryKeyFactory.newsletters.lists(),
            refetchType: 'active',
          })
        );
        break;
    }
 
    Promise.all(invalidationPromises).catch((error) => {
      this.log.error(
        'Failed to invalidate related queries',
        {
          action: 'invalidate_related_queries',
          metadata: {
            newsletterIds,
            invalidationCount: invalidationPromises.length,
          },
        },
        error
      );
    });
  }
 
  // Smart invalidation that respects filter context
  smartInvalidate(options: {
    operation: string;
    newsletterIds?: string[];
    filterContext?: unknown;
    priority: 'high' | 'medium' | 'low';
  }): void {
    const { operation, newsletterIds = [], filterContext, priority } = options;
 
    this.log.debug('Smart cache invalidation triggered', {
      action: 'smart_invalidation',
      metadata: {
        operation,
        newsletterCount: newsletterIds.length,
        filterContext,
        priority,
      },
    });
 
    switch (operation) {
      case 'newsletter-action':
        // For newsletter actions, preserve the current filter state
        // Only invalidate unread counts, let optimistic updates handle the rest
        this.queryClient.invalidateQueries({
          queryKey: ['unreadCount'],
          refetchType: priority === 'high' ? 'active' : 'none',
        });
 
        // Gentle refresh of current newsletter list after a delay
        if (priority === 'high') {
          setTimeout(() => {
            this.queryClient.refetchQueries({
              queryKey: queryKeyFactory.newsletters.lists(),
              type: 'active',
            });
          }, 500);
        }
        break;
 
      case 'queue-action':
        // For reading queue actions, invalidate queue and unread counts
        this.queryClient.invalidateQueries({
          queryKey: queryKeyFactory.queue.all(),
          refetchType: priority === 'high' ? 'active' : 'none',
        });
        this.queryClient.invalidateQueries({
          queryKey: ['unreadCount'],
          refetchType: 'active',
        });
        break;
 
      default:
        // Fallback to standard invalidation
        this.invalidateRelatedQueries(newsletterIds, operation);
        break;
    }
  }
 
  // Handle archive operations with filter-aware cache updates
  private handleArchiveInvalidation(newsletterIds: string[], operationType: string): void {
    const isArchiving =
      operationType === 'toggle-archive' ||
      operationType === 'archive' ||
      operationType === 'bulk-archive';
 
    // Update all newsletter list queries to remove/add archived items based on filter context
    this.queryClient.setQueriesData<PaginatedResponse<NewsletterWithRelations>>(
      { queryKey: queryKeyFactory.newsletters.lists() },
      (oldData) => {
        if (!oldData || !oldData.data || !Array.isArray(oldData.data)) return oldData;
 
        // Get the filter context from the query key to understand if archived items should be shown
        const shouldShowArchived = this.shouldShowArchivedInQuery(oldData);
 
        if (isArchiving && !shouldShowArchived) {
          // Remove archived newsletters from non-archived views
          const filteredData = oldData.data.filter(
            (newsletter: NewsletterWithRelations) => !newsletterIds.includes(newsletter.id)
          );
          return {
            ...oldData,
            data: filteredData,
            count: Math.max(0, (oldData.count || 0) - newsletterIds.length),
          };
        } else if (!isArchiving && shouldShowArchived) {
          // For unarchive operations in archived view, let optimistic updates handle it
          // The newsletters will still show until the actual refetch happens
          return oldData;
        }
 
        return oldData;
      }
    );
  }
 
  // Handle delete operations by completely removing items from all caches
  private handleDeleteInvalidation(newsletterIds: string[]): void {
    // Remove from all newsletter list queries
    this.queryClient.setQueriesData<unknown>(
      { queryKey: queryKeyFactory.newsletters.lists() },
      (oldData: unknown) => {
        if (!oldData || !(oldData as any)?.data || !Array.isArray((oldData as any).data))
          return oldData;
 
        const filteredData = (oldData as any).data.filter(
          (newsletter: NewsletterWithRelations) => !newsletterIds.includes(newsletter.id)
        );
 
        return {
          ...(oldData as any),
          data: filteredData,
          count: Math.max(0, ((oldData as any).count || 0) - newsletterIds.length),
        };
      }
    );
 
    // Remove individual newsletter detail caches
    newsletterIds.forEach((id) => {
      this.queryClient.removeQueries({
        queryKey: queryKeyFactory.newsletters.detail(id),
        exact: true,
      });
    });
 
    // Remove from reading queue if present
    this.queryClient.setQueriesData<ReadingQueueItem[]>(
      { queryKey: queryKeyFactory.queue.all() },
      (oldData) => {
        if (!Array.isArray(oldData)) return oldData;
        return oldData.filter((item) => !newsletterIds.includes(item.newsletter_id));
      }
    );
  }
 
  // Determine if a query should show archived newsletters based on its filter context
  private shouldShowArchivedInQuery(
    queryData: PaginatedResponse<NewsletterWithRelations>
  ): boolean {
    // This is a heuristic - in a real implementation, you'd parse the query key
    // to understand the filter context. For now, we assume if the data contains
    // archived newsletters, it's an "all" or "archived" view
    if (!(queryData as any)?.data || !Array.isArray((queryData as any).data)) return false;
 
    const hasArchivedNewsletters = (queryData as any).data.some(
      (newsletter: NewsletterWithRelations) => newsletter.is_archived === true
    );
 
    return hasArchivedNewsletters;
  }
 
  // Optimistic update with rollback support
  async optimisticUpdate(
    newsletterId: string,
    updates: Partial<NewsletterWithRelations>,
    operation: string
  ): Promise<NewsletterWithRelations | null> {
    try {
      this.log.debug('Starting optimistic update', {
        action: 'optimistic_update_start',
        metadata: {
          newsletterId,
          operation,
          updates,
          updateFields: Object.keys(updates),
        },
      });
 
      // Get all query keys that might contain this newsletter
      const queryCache = this.queryClient.getQueryCache();
      const queries = queryCache.findAll({
        predicate: (query) => {
          const key = query.queryKey;
          // Match any query key that's for newsletter lists or infinite lists
          if (!Array.isArray(key) || key.length < 2) return false;
 
          // Check for regular list queries
          if (key[0] === 'newsletters' && key[1] === 'list' && key[2] !== 'infinite') {
            return true;
          }
 
          // Check for infinite queries
          if (key[0] === 'newsletters' && key[1] === 'list' && key[2] === 'infinite') {
            return true;
          }
 
          return false;
        },
      });
 
      // Find the first query that contains our newsletter
      let currentData: NewsletterWithRelations | null = null;
 
      for (const query of queries) {
        // Check if it's an infinite query
        const queryKey = query.queryKey;
        if (
          Array.isArray(queryKey) &&
          queryKey.length >= 3 &&
          queryKey[0] === 'newsletters' &&
          queryKey[1] === 'list' &&
          queryKey[2] === 'infinite'
        ) {
          const data = this.queryClient.getQueryData<{
            pages: PaginatedResponse<NewsletterWithRelations>[];
          }>(query.queryKey);
 
          if (data?.pages) {
            for (const page of data.pages) {
              const newsletter = page.data.find((n) => n.id === newsletterId);
              if (newsletter) {
                currentData = newsletter;
                break;
              }
            }
            if (currentData) break;
          }
        } else {
          // Regular list query
          const data = this.queryClient.getQueryData<
            PaginatedResponse<NewsletterWithRelations> | NewsletterWithRelations[] | undefined
          >(query.queryKey);
 
          if (data) {
            const newsletters = Array.isArray(data) ? data : data.data;
            if (Array.isArray(newsletters)) {
              const newsletter = newsletters.find((n) => n.id === newsletterId);
              if (newsletter) {
                currentData = newsletter;
                break;
              }
            }
          }
        }
      }
 
      // Update newsletter in all relevant caches
      this.updateNewsletterInCache({ id: newsletterId, updates });
 
      // Don't invalidate queries immediately for optimistic updates
      // The calling code will handle invalidation after the API call
 
      this.log.debug('Optimistic update completed', {
        action: 'optimistic_update_complete',
        metadata: {
          newsletterId,
          operation,
          foundOriginalData: currentData !== null,
          originalValues: currentData
            ? {
              is_read: currentData.is_read,
              is_liked: currentData.is_liked,
              is_archived: currentData.is_archived,
            }
            : null,
        },
      });
 
      return currentData;
    } catch (error) {
      this.log.error(
        'Failed to perform optimistic update',
        {
          action: 'optimistic_update',
          metadata: { operation },
        },
        error instanceof Error ? error : new Error(String(error))
      );
      return null;
    }
  }
 
  // Warm cache by prefetching common queries
  warmCache(userId: string, priority: 'high' | 'medium' | 'low' = 'medium'): void {
    if (!userId) return;
 
    const prefetchOptions = {
      staleTime: priority === 'high' ? 10 * 60 * 1000 : 5 * 60 * 1000, // 10 min for high, 5 min for others
    };
 
    // Prefetch newsletters
    this.queryClient.prefetchQuery({
      queryKey: queryKeyFactory.newsletters.list({ userId }),
      queryFn: () => Promise.resolve([]), // Would be actual fetch function
      ...prefetchOptions,
    });
 
    // Prefetch reading queue if high priority
    if (priority === 'high') {
      this.queryClient.prefetchQuery({
        queryKey: queryKeyFactory.queue.list(userId),
        queryFn: () => Promise.resolve([]), // Would be actual fetch function
        ...prefetchOptions,
      });
    }
 
    // Prefetch unread count
    this.queryClient.prefetchQuery({
      queryKey: ['unreadCount', userId],
      queryFn: () => Promise.resolve(0), // Would be actual fetch function
      ...prefetchOptions,
    });
  }
 
  // Clear specific cache sections
  clearNewsletterCache(): void {
    this.queryClient.invalidateQueries({
      queryKey: queryKeyFactory.newsletters.lists(),
      refetchType: 'active',
    });
  }
 
  clearReadingQueueCache(): void {
    this.queryClient.invalidateQueries({
      queryKey: queryKeyFactory.queue.all(),
      refetchType: 'active',
    });
  }
 
  // Tag-specific cache operations
  invalidateTagQueries(): void {
    this.queryClient.invalidateQueries({
      queryKey: queryKeyFactory.newsletters.tags(),
      refetchType: 'active',
    });
    this.queryClient.invalidateQueries({
      queryKey: ['newsletter_tags'],
      refetchType: 'active',
    });
  }
 
  updateNewsletterTagsInCache(newsletterId: string, tags: Tag[]): void {
    // Update newsletter with new tags in all caches
    this.updateNewsletterInCache({
      id: newsletterId,
      updates: { tags },
    });
 
    // Invalidate tag-related queries
    this.invalidateTagQueries();
  }
 
  removeTagFromAllNewsletters(tagId: string): void {
    // Update all newsletter list queries to remove the deleted tag
    this.queryClient.setQueriesData<NewsletterWithRelations[]>(
      { queryKey: queryKeyFactory.newsletters.lists() },
      (oldData) => {
        if (!oldData) return oldData;
        return oldData.map((newsletter) => ({
          ...newsletter,
          tags: newsletter.tags?.filter((tag) => tag.id !== tagId) || [],
        }));
      }
    );
 
    // Update individual newsletter queries
    this.queryClient
      .getQueryCache()
      .findAll()
      .forEach((query) => {
        if (query.queryKey[0] === 'newsletters' && query.queryKey[1] === 'detail') {
          const newsletterData = query.state.data as NewsletterWithRelations;
          if (newsletterData?.tags?.some((tag) => tag.id === tagId)) {
            this.queryClient.setQueryData<NewsletterWithRelations>(query.queryKey, (oldData) => {
              if (!oldData) return oldData;
              return {
                ...oldData,
                tags: oldData.tags?.filter((tag) => tag.id !== tagId) || [],
              };
            });
          }
        }
      });
 
    // Invalidate tag-related queries
    this.invalidateTagQueries();
  }
 
  // Enhanced cache invalidation for granular control
  invalidateNewsletterListQueries(filters?: Record<string, any>): Promise<void> {
    const queryKey = filters
      ? queryKeyFactory.newsletters.list(filters)
      : queryKeyFactory.newsletters.lists();
 
    return this.queryClient.invalidateQueries({
      queryKey,
      refetchType: 'active',
    });
  }
 
  // Batch invalidation for multiple operations
  async batchInvalidateQueries(
    operations: Array<{
      type: string;
      ids: string[];
      filters?: Record<string, any>;
    }>
  ): Promise<void> {
    const promises = operations.map(({ type, ids, filters }) => {
      switch (type) {
        case 'newsletter-list':
          return this.invalidateNewsletterListQueries(filters);
        case 'newsletter-detail':
          return Promise.all(
            ids.map((id) =>
              this.queryClient.invalidateQueries({
                queryKey: queryKeyFactory.newsletters.detail(id),
                refetchType: 'active',
              })
            )
          );
        case 'reading-queue':
          return this.queryClient.invalidateQueries({
            queryKey: queryKeyFactory.queue.all(),
            refetchType: 'active',
          });
        case 'unread-count':
          return this.queryClient.invalidateQueries({
            queryKey: ['unreadCount'],
            refetchType: 'active',
          });
        default:
          return Promise.resolve();
      }
    });
 
    await Promise.all(promises);
  }
 
  // Optimistic update with enhanced rollback
  async optimisticUpdateWithRollback<T>(
    queryKey: unknown[],
    updater: (data: T) => T,
    rollbackData?: T
  ): Promise<{ rollback: () => void; previousData: T | undefined }> {
    const previousData = this.queryClient.getQueryData<T>(queryKey);
 
    // Apply optimistic update
    this.queryClient.setQueryData<T>(queryKey, updater as any);
 
    const rollback = () => {
      if (rollbackData !== undefined) {
        this.queryClient.setQueryData<T>(queryKey, rollbackData);
      } else if (previousData !== undefined) {
        this.queryClient.setQueryData<T>(queryKey, previousData);
      }
    };
 
    return { rollback, previousData };
  }
}
 
// Singleton instance
let cacheManagerInstance: SimpleCacheManager | null = null;
 
export const createCacheManager = (
  queryClient: QueryClient,
  config?: CacheManagerConfig
): SimpleCacheManager => {
  cacheManagerInstance = new SimpleCacheManager(queryClient, config);
  return cacheManagerInstance;
};
 
export const getCacheManager = (): SimpleCacheManager => {
  if (!cacheManagerInstance) {
    throw new Error('Cache manager not initialized. Call createCacheManager first.');
  }
  return cacheManagerInstance;
};
 
export const getCacheManagerSafe = (): SimpleCacheManager | null => {
  return cacheManagerInstance;
};
 
// Reset function for testing purposes
export const resetCacheManager = (): void => {
  cacheManagerInstance = null;
};
 
// Additional cache utility methods
export const prefetchQuery = async <T>(
  queryKey: readonly unknown[],
  queryFn: () => Promise<T>,
  options: { staleTime?: number; gcTime?: number } = {}
): Promise<void> => {
  const manager = getCacheManager();
  await manager.queryClient.prefetchQuery({
    queryKey,
    queryFn,
    staleTime: options.staleTime || 5 * 60 * 1000,
    gcTime: options.gcTime || 30 * 60 * 1000,
  });
};
 
export const getQueryData = <T>(queryKey: readonly unknown[]): T | undefined => {
  const manager = getCacheManager();
  return manager.queryClient.getQueryData<T>(queryKey);
};
 
export const getQueriesData = <T>(
  queryKey: readonly unknown[]
): [readonly unknown[], T | undefined][] => {
  const manager = getCacheManager();
  return manager.queryClient.getQueriesData<T>({ queryKey });
};
 
export const getQueryState = (queryKey: readonly unknown[]) => {
  const manager = getCacheManager();
  return manager.queryClient.getQueryState(queryKey);
};
 
export const invalidateQueries = async (options: {
  queryKey?: readonly unknown[];
  predicate?: (query: { queryKey: unknown[] }) => boolean;
  refetchType?: 'active' | 'inactive' | 'all';
}): Promise<void> => {
  const manager = getCacheManager();
  await manager.queryClient.invalidateQueries(
    options as Parameters<typeof manager.queryClient.invalidateQueries>[0]
  );
};
 
export const setQueryData = <T>(
  queryKey: readonly unknown[],
  data: T | ((oldData: T | undefined) => T)
): void => {
  const manager = getCacheManager();
  manager.queryClient.setQueryData<T>(queryKey, data);
};
 
export const cancelQueries = async (options: {
  queryKey?: readonly unknown[];
  predicate?: (query: { queryKey: unknown[] }) => boolean;
  refetchType?: 'active' | 'inactive' | 'all';
}): Promise<void> => {
  const manager = getCacheManager();
  await manager.queryClient.cancelQueries(
    options as Parameters<typeof manager.queryClient.cancelQueries>[0]
  );
};
 
// Utility function to get current unread count from cache
export const getCurrentUnreadCount = (): { total: number; bySource: Record<string, number> } | undefined => {
  const manager = getCacheManager();
  return manager.queryClient.getQueryData<{ total: number; bySource: Record<string, number> }>(['unreadCount', 'all']);
};
 
// Utility functions for backward compatibility
export const updateCachedNewsletter = (
  newsletterId: string,
  updates: Partial<NewsletterWithRelations>
) => {
  const manager = getCacheManager();
  manager.updateNewsletterInCache({ id: newsletterId, updates });
};
 
export const updateMultipleCachedNewsletters = async (
  updates: { id: string; updates: Partial<NewsletterWithRelations> }[]
) => {
  const manager = getCacheManager();
  await manager.batchUpdateNewsletters(updates);
};
 
export const invalidateNewsletterQueries = (newsletterIds: string[], operationType: string) => {
  const manager = getCacheManager();
  manager.invalidateRelatedQueries(newsletterIds, operationType);
};