All files / src/common/hooks useReadingQueue.ts

69.69% Statements 276/396
68.91% Branches 51/74
84.37% Functions 27/32
69.69% Lines 276/396

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 4881x 1x 1x   1x 1x 1x 1x 1x 1x   1x 35x 35x 35x     35x 33x 35x     35x 35x 12x 12x 12x 12x 35x 35x     35x   35x 3x 35x   35x 35x 3x 3x                       3x 35x 35x     35x 13x 13x 13x 1x 1x 1x 1x 1x 1x 1x 1x     1x   1x                           1x 1x 1x 1x 1x 1x 1x 1x         35x     35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x   1x       1x 1x 35x 35x     35x 35x 1x   1x 1x 1x 1x 1x 1x 1x 35x 1x     1x     1x 1x 1x 1x 1x 1x 1x   1x 1x 35x                                                 35x 1x     1x 35x 1x   1x 1x 35x     35x 35x 1x 1x 1x 1x 1x 1x 1x 1x 35x 1x     1x 1x     1x 1x 1x 1x 1x 1x 1x   1x 1x 35x                                                 35x 1x     1x 35x 1x   1x 1x 35x     35x 35x 1x   1x 1x 1x 1x 1x 1x 1x 35x 1x     1x     1x 1x 1x 1x 1x 1x 1x   1x 1x 35x                                                 35x 1x   1x 1x 35x     35x 35x 1x 1x 1x 35x 1x 1x 35x     35x 35x 1x 1x 35x 1x 1x 35x     35x 35x 1x 1x 35x 1x 1x 35x     35x 35x 1x   1x 1x 1x 1x   1x 1x 35x   1x     1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 35x                         35x   1x 1x 35x     35x 35x 1x 1x 1x 35x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 35x                   35x 1x 1x 35x     35x 35x 1x   1x 1x 1x                     1x 35x 35x   35x   35x 35x 35x 35x 35x     35x 35x 35x 35x 35x 35x 35x 35x 35x     35x 35x 35x 35x 35x 35x 35x 35x     35x 35x 35x  
import { AuthContext } from '@common/contexts/AuthContext';
import { readingQueueService } from '@common/services';
import { optimizedNewsletterService } from '@common/services/optimizedNewsletterService';
import type { ReadingQueueItem } from '@common/types';
import { useLogger } from '@common/utils/logger/useLogger';
import { updateNewsletterTags } from '@common/utils/tagUtils';
import { useMutation, useQuery } from '@tanstack/react-query';
import { useCallback, useContext, useMemo, useRef } from 'react';
import { getCacheManagerSafe } from '../utils/cacheUtils';
import { queryKeyFactory } from '../utils/queryKeyFactory';
 
export const useReadingQueue = () => {
  const auth = useContext(AuthContext);
  const user = auth?.user;
  const log = useLogger();
 
  // Initialize cache manager safely
  const cacheManager = useMemo(() => {
    return getCacheManagerSafe();
  }, []);
 
  // Safe cache manager helper
  const safeCacheCall = useCallback(
    (fn: (manager: NonNullable<ReturnType<typeof getCacheManagerSafe>>) => void) => {
      if (cacheManager) {
        fn(cacheManager);
      }
    },
    [cacheManager]
  );
 
  // Performance monitoring
  const performanceTimers = useRef<Map<string, number>>(new Map());
 
  const startTimer = useCallback((operation: string) => {
    performanceTimers.current.set(operation, performance.now());
  }, []);
 
  const endTimer = useCallback(
    (operation: string) => {
      const start = performanceTimers.current.get(operation);
      if (start && process.env.NODE_ENV === 'development') {
        const duration = performance.now() - start;
        log.debug('Reading queue operation completed', {
          action: 'performance_timer',
          metadata: {
            operation,
            duration: duration.toFixed(2),
            unit: 'ms',
          },
        });
        performanceTimers.current.delete(operation);
      }
    },
    [log]
  );
 
  // Helper function to fetch reading queue
  const fetchReadingQueue = useCallback(async (): Promise<ReadingQueueItem[]> => {
    try {
      return await readingQueueService.getAll();
    } catch (error) {
      log.error(
        'Failed to fetch reading queue',
        {
          action: 'fetch_reading_queue',
          metadata: { userId: user?.id },
        },
        error instanceof Error ? error : new Error(String(error))
      );
 
      // Handle specific error types
      if (error instanceof Error) {
        // If it's a null newsletter error, it means data integrity issues
        if (error.message.includes('not found in reading queue item')) {
          log.warn('Data integrity issue in reading queue', {
            action: 'data_integrity_check',
            metadata: {
              userId: user?.id,
              issue: 'missing_newsletter_in_queue_item',
              resolution: 'returning_empty_queue',
            },
          });
          // Could potentially trigger a cleanup here if needed
          return [];
        }
 
        // If it's a network/auth error, re-throw to let React Query handle retries
        if (
          error.message.includes('JWT') ||
          error.message.includes('auth') ||
          error.message.includes('network')
        ) {
          throw error;
        }
      }
 
      // For other errors, return empty array to prevent UI breaks
      return [];
    }
  }, [log, user?.id]);
 
  // Query for reading queue
  const {
    data: readingQueue = [],
    isLoading,
    isError,
    error,
    refetch,
  } = useQuery<ReadingQueueItem[], Error>({
    queryKey: queryKeyFactory.queue.list(user?.id || ''),
    queryFn: () => fetchReadingQueue(),
    enabled: !!user?.id,
    staleTime: 1 * 60 * 1000, // 1 minute
    gcTime: 5 * 60 * 1000, // 5 minutes
    refetchOnWindowFocus: false,
    retry: (failureCount, error) => {
      // Don't retry on data integrity errors
      if (error instanceof Error && error.message.includes('not found in reading queue item')) {
        return false;
      }
      // Retry up to 3 times for other errors
      return failureCount < 3;
    },
    retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
  });
 
  // Add to reading queue
  const addToQueue = useMutation({
    mutationFn: async (newsletterId: string) => {
      if (!user?.id) throw new Error('User not authenticated');
 
      startTimer('addToQueue');
      try {
        return await readingQueueService.add(newsletterId);
      } finally {
        endTimer('addToQueue');
      }
    },
    onMutate: async (newsletterId) => {
      if (!user?.id) return;
 
      // Snapshot the previous queue
      const previousQueue = readingQueue;
 
      // Use cache manager for optimistic update
      safeCacheCall((manager) =>
        manager.updateReadingQueueInCache({
          type: 'add',
          newsletterId,
          userId: user.id,
        })
      );
 
      return { previousQueue };
    },
    onError: (error, _newsletterId, context) => {
      log.error(
        'Failed to add newsletter to reading queue',
        {
          action: 'add_to_queue',
          metadata: {
            newsletterId: _newsletterId,
            userId: user?.id,
            hasContext: !!context?.previousQueue,
          },
        },
        error
      );
 
      // Revert optimistic update using cache manager
      if (context?.previousQueue && user?.id) {
        safeCacheCall((manager) =>
          manager.updateReadingQueueInCache({
            type: 'revert',
            queueItems: context.previousQueue,
            userId: user.id,
          })
        );
      }
    },
    onSuccess: (_data) => {
      if (!user) return;
 
      // Reading queue status is now managed separately from newsletter properties
    },
    onSettled: () => {
      if (!user) return;
      // Use cache manager for smart invalidation
      safeCacheCall((manager) => manager.invalidateRelatedQueries([], 'queue-add'));
    },
  });
 
  // Remove from reading queue
  const removeFromQueue = useMutation({
    mutationFn: async (queueItemId: string) => {
      if (!user?.id) throw new Error('User not authenticated');
      startTimer('removeFromQueue');
      try {
        return await readingQueueService.remove(queueItemId);
      } finally {
        endTimer('removeFromQueue');
      }
    },
    onMutate: async (queueItemId) => {
      if (!user) return;
 
      // Find the item being removed
      const itemToRemove = readingQueue.find((item) => item.id === queueItemId);
      const previousQueue = readingQueue;
 
      // Use cache manager for optimistic removal
      safeCacheCall((manager) =>
        manager.updateReadingQueueInCache({
          type: 'remove',
          queueItemId,
          userId: user.id,
        })
      );
 
      return { previousQueue, removedItem: itemToRemove };
    },
    onError: (error, _queueItemId, context) => {
      log.error(
        'Failed to remove newsletter from reading queue',
        {
          action: 'remove_from_queue',
          metadata: {
            queueItemId: _queueItemId,
            userId: user?.id,
            hasContext: !!context?.previousQueue,
          },
        },
        error
      );
 
      // Revert optimistic update using cache manager
      if (context?.previousQueue && user?.id) {
        safeCacheCall((manager) =>
          manager.updateReadingQueueInCache({
            type: 'revert',
            queueItems: context.previousQueue,
            userId: user.id,
          })
        );
      }
    },
    onSuccess: (_data, _queueItemId, context) => {
      if (!user || !context?.removedItem) return;
 
      // Reading queue status is now managed separately from newsletter properties
    },
    onSettled: () => {
      if (!user) return;
      // Use cache manager for smart invalidation
      safeCacheCall((manager) => manager.invalidateRelatedQueries([], 'queue-remove'));
    },
  });
 
  // Reorder reading queue
  const reorderQueue = useMutation({
    mutationFn: async (updates: { id: string; position: number }[]) => {
      if (!user) throw new Error('User not authenticated');
 
      startTimer('reorderQueue');
      try {
        return await readingQueueService.reorder(updates);
      } finally {
        endTimer('reorderQueue');
      }
    },
    onMutate: async (updates) => {
      if (!user?.id) return;
 
      // Snapshot the previous queue
      const previousQueue = readingQueue;
 
      // Use cache manager for optimistic reordering
      safeCacheCall((manager) =>
        manager.updateReadingQueueInCache({
          type: 'reorder',
          updates,
          userId: user.id,
        })
      );
 
      return { previousQueue };
    },
    onError: (error, _updates, context) => {
      log.error(
        'Failed to reorder reading queue',
        {
          action: 'reorder_queue',
          metadata: {
            userId: user?.id,
            updatesCount: _updates?.length || 0,
            hasContext: !!context?.previousQueue,
          },
        },
        error
      );
 
      // Revert optimistic update using cache manager
      if (context?.previousQueue && user?.id) {
        safeCacheCall((manager) =>
          manager.updateReadingQueueInCache({
            type: 'revert',
            queueItems: context.previousQueue,
            userId: user.id,
          })
        );
      }
    },
    onSettled: () => {
      if (!user?.id) return;
      // Use cache manager for smart invalidation
      safeCacheCall((manager) => manager.invalidateRelatedQueries([], 'queue-reorder'));
    },
  });
 
  // Clear entire reading queue
  const clearQueue = useMutation({
    mutationFn: async () => {
      if (!user?.id) throw new Error('User not authenticated');
      return readingQueueService.clear();
    },
    onSuccess: () => {
      safeCacheCall((manager) => manager.invalidateRelatedQueries([], 'queue-clear'));
    },
  });
 
  // Mark newsletter as read
  const markAsRead = useMutation({
    mutationFn: async (newsletterId: string) => {
      return optimizedNewsletterService.markAsRead(newsletterId);
    },
    onSuccess: () => {
      safeCacheCall((manager) => manager.invalidateRelatedQueries([], 'queue-mark-read'));
    },
  });
 
  // Mark newsletter as unread
  const markAsUnread = useMutation({
    mutationFn: async (newsletterId: string) => {
      return optimizedNewsletterService.markAsUnread(newsletterId);
    },
    onSuccess: () => {
      safeCacheCall((manager) => manager.invalidateRelatedQueries([], 'queue-mark-unread'));
    },
  });
 
  // Update tags
  const updateTags = useMutation({
    mutationFn: async ({ newsletterId, tagIds }: { newsletterId: string; tagIds: string[] }) => {
      if (!user?.id) throw new Error('User not authenticated');
 
      const currentTagIds =
        readingQueue
          .find((item) => item.newsletter.id === newsletterId)
          ?.newsletter.tags?.map((tag) => tag.id) || [];
 
      return updateNewsletterTags(newsletterId, tagIds, currentTagIds, user.id);
    },
    onMutate: async ({ newsletterId, tagIds }) => {
      // Snapshot the previous value
      const previousQueue = readingQueue;
 
      // Use cache manager for optimistic tag update
      safeCacheCall((manager) =>
        manager.updateReadingQueueInCache({
          type: 'updateTags',
          newsletterId,
          tagIds,
          userId: user?.id || '',
        })
      );
 
      return { previousQueue };
    },
    onError: (_err, _variables, context) => {
      // Rollback on error
      if (context?.previousQueue) {
        // Revert using cache manager
        safeCacheCall((manager) =>
          manager.updateReadingQueueInCache({
            type: 'revert',
            queueItems: context.previousQueue,
            userId: user?.id || '',
          })
        );
      }
    },
    onSettled: () => {
      // Use cache manager for smart invalidation
      safeCacheCall((manager) => manager.invalidateRelatedQueries([], 'queue-update-tags'));
    },
  });
 
  // Cleanup orphaned items
  const cleanupOrphanedItems = useMutation({
    mutationFn: async () => {
      if (!user?.id) throw new Error('User not authenticated');
      return readingQueueService.cleanupOrphanedItems();
    },
    onSuccess: (result) => {
      if (result.removedCount > 0) {
        log.info('Cleaned up orphaned reading queue items', {
          action: 'cleanup_orphaned_items',
          metadata: {
            removedCount: result.removedCount,
            userId: user?.id,
          },
        });
        // Refetch the queue to get the updated state
        refetch();
      }
    },
    onError: (error) => {
      log.error(
        'Failed to cleanup orphaned reading queue items',
        {
          action: 'cleanup_orphaned_items',
          metadata: { userId: user?.id },
        },
        error
      );
    },
    onSettled: () => {
      safeCacheCall((manager) => manager.invalidateRelatedQueries([], 'queue-cleanup'));
    },
  });
 
  // Check if newsletter is in queue
  const isInQueue = useCallback(
    async (newsletterId: string): Promise<boolean> => {
      if (!user) return false;
 
      try {
        return await readingQueueService.isInQueue(newsletterId);
      } catch (error) {
        log.error(
          'Failed to check if newsletter is in queue',
          {
            action: 'check_is_in_queue',
            metadata: { newsletterId, userId: user.id },
          },
          error instanceof Error ? error : new Error(String(error))
        );
        return false;
      }
    },
    [user, log]
  );
 
  return {
    // Data
    readingQueue,
    isLoading,
    isError,
    error,
    isEmpty: readingQueue.length === 0,
 
    // Actions
    addToQueue: addToQueue.mutateAsync,
    removeFromQueue: removeFromQueue.mutateAsync,
    reorderQueue: reorderQueue.mutateAsync,
    clearQueue: clearQueue.mutateAsync,
    markAsRead: markAsRead.mutateAsync,
    markAsUnread: markAsUnread.mutateAsync,
    updateTags: updateTags.mutateAsync,
    cleanupOrphanedItems: cleanupOrphanedItems.mutateAsync,
    isInQueue,
 
    // Loading states
    isAdding: addToQueue.isPending,
    isRemoving: removeFromQueue.isPending,
    isReordering: reorderQueue.isPending,
    isClearing: clearQueue.isPending,
    isMarkingAsRead: markAsRead.isPending,
    isMarkingAsUnread: markAsUnread.isPending,
    isUpdatingTags: updateTags.isPending,
    isCleaningUp: cleanupOrphanedItems.isPending,
 
    // Utils
    refetch,
  };
};