import { mutationOptions } from '@tanstack/react-query';
import { getQueryClient } from '@/lib/query-client';
import {
  archiveNotificationItem,
  markAllNotificationsRead,
  markNotificationRead
} from './service';
import { notificationKeys } from './queries';

async function invalidateNotifications() {
  await Promise.all([
    getQueryClient().invalidateQueries({ queryKey: notificationKeys.lists() }),
    getQueryClient().invalidateQueries({ queryKey: notificationKeys.unreadCount() })
  ]);
}

export const markNotificationReadMutation = mutationOptions({
  mutationFn: (id: string) => markNotificationRead(id),
  onSettled: async (_data, error) => {
    if (!error) {
      await invalidateNotifications();
    }
  }
});

export const markAllNotificationsReadMutation = mutationOptions({
  mutationFn: () => markAllNotificationsRead(),
  onSettled: async (_data, error) => {
    if (!error) {
      await invalidateNotifications();
    }
  }
});

export const archiveNotificationMutation = mutationOptions({
  mutationFn: (id: string) => archiveNotificationItem(id),
  onSettled: async (_data, error) => {
    if (!error) {
      await invalidateNotifications();
    }
  }
});
