"use client" import { useMutation, useQueryClient } from "@tanstack/react-query" import { createSupabaseBrowserClient } from "@/lib/supabase/client" import { toast } from "sonner" import { queryKeys } from "./query-keys" import { notify } from "@/lib/notify" export function useMarkAllAsRead() { const supabaseClient = createSupabaseBrowserClient() const queryClient = useQueryClient() return useMutation({ mutationFn: async ({ feedIdentifier, folderIdentifier, readState = true, entryIdentifiers, }: { feedIdentifier?: string | null folderIdentifier?: string | null readState?: boolean entryIdentifiers?: string[] } = {}) => { const { data, error } = await supabaseClient.rpc("mark_all_as_read", { p_feed_id: feedIdentifier ?? null, p_folder_id: folderIdentifier ?? null, p_read_state: readState, p_entry_ids: entryIdentifiers ?? null, }) if (error) throw error return (data as string[]) ?? [] }, onSuccess: (affectedEntryIdentifiers, variables) => { queryClient.invalidateQueries({ queryKey: queryKeys.timeline.all }) queryClient.invalidateQueries({ queryKey: queryKeys.unreadCounts.all }) queryClient.invalidateQueries({ queryKey: queryKeys.savedEntries.all }) const action = variables?.readState === false ? "unread" : "read" const undoReadState = !(variables?.readState ?? true) if (affectedEntryIdentifiers.length > 0) { toast(`marked ${affectedEntryIdentifiers.length} ${affectedEntryIdentifiers.length === 1 ? "entry" : "entries"} as ${action}`, { action: { label: "undo", onClick: () => { supabaseClient .rpc("mark_all_as_read", { p_feed_id: null, p_folder_id: null, p_read_state: undoReadState, p_entry_ids: affectedEntryIdentifiers, }) .then(() => { queryClient.invalidateQueries({ queryKey: queryKeys.timeline.all }) queryClient.invalidateQueries({ queryKey: queryKeys.unreadCounts.all }) queryClient.invalidateQueries({ queryKey: queryKeys.savedEntries.all }) }) }, }, }) } }, onError: (_, variables) => { const action = variables?.readState === false ? "unread" : "read" notify(`failed to mark entries as ${action}`) }, }) }