import { useMutation, useQueryClient, type QueryKey } from '@tanstack/react-query';
import type { Paginated } from '@/lib/api/types';
import { notificationKeys } from '../keys';
import { notificationsApi } from '../apis';
import type { AppNotification } from '../types';

interface MarkAllContext {
  prevCount?: number;
  prevLists: Array<[QueryKey, Paginated<AppNotification> | undefined]>;
}

/**
 * "Mark all read" — **optimistic**: flip every cached list item to `isRead` and zero the cached unread count
 * so the badge clears instantly, roll both back on error, and invalidate on settle.
 */
export function useMarkAllRead() {
  const queryClient = useQueryClient();
  return useMutation<void, unknown, void, MarkAllContext>({
    mutationFn: () => notificationsApi.markAllRead(),

    onMutate: async () => {
      await queryClient.cancelQueries({ queryKey: notificationKeys.all });
      const prevCount = queryClient.getQueryData<number>(notificationKeys.unreadCount());
      const prevLists = queryClient.getQueriesData<Paginated<AppNotification>>({ queryKey: notificationKeys.lists() });

      queryClient.setQueriesData<Paginated<AppNotification>>({ queryKey: notificationKeys.lists() }, (data) =>
        data ? { ...data, items: data.items.map((n) => ({ ...n, isRead: true })) } : data,
      );
      queryClient.setQueryData<number>(notificationKeys.unreadCount(), 0);
      return { prevCount, prevLists };
    },

    onError: (_err, _vars, context) => {
      if (context?.prevCount !== undefined) queryClient.setQueryData(notificationKeys.unreadCount(), context.prevCount);
      context?.prevLists.forEach(([key, data]) => queryClient.setQueryData(key, data));
    },

    onSettled: () => {
      queryClient.invalidateQueries({ queryKey: notificationKeys.lists() });
      queryClient.invalidateQueries({ queryKey: notificationKeys.unreadCount() });
    },
  });
}
