"use client";

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useDataProvider, useQueryKeyPrefix } from '@/lib/demo/data-provider-context';
import type { UpdatePreferencesRequest } from '@/lib/api/notifications';

export function useNotifications(limit?: number) {
  const { notifications } = useDataProvider();
  const qk = useQueryKeyPrefix();
  return useQuery({
    queryKey: qk('notifications', limit),
    queryFn: () => notifications.list(limit),
  });
}

export function useUnreadCount() {
  const { notifications } = useDataProvider();
  const qk = useQueryKeyPrefix();
  return useQuery({
    queryKey: qk('notifications', 'unread-count'),
    queryFn: () => notifications.getUnreadCount(),
    refetchInterval: 60_000,
  });
}

export function useNotificationPreferences() {
  const { notifications } = useDataProvider();
  const qk = useQueryKeyPrefix();
  return useQuery({
    queryKey: qk('notifications', 'preferences'),
    queryFn: () => notifications.getPreferences(),
  });
}

export function useUpdatePreferences() {
  const queryClient = useQueryClient();
  const { notifications } = useDataProvider();
  const qk = useQueryKeyPrefix();
  return useMutation({
    mutationFn: (data: UpdatePreferencesRequest) => notifications.updatePreferences(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: qk('notifications', 'preferences') });
    },
  });
}

export function useMarkAsRead() {
  const queryClient = useQueryClient();
  const { notifications } = useDataProvider();
  const qk = useQueryKeyPrefix();
  return useMutation({
    mutationFn: (id: number) => notifications.markAsRead(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: qk('notifications') });
      queryClient.invalidateQueries({ queryKey: qk('notifications', 'unread-count') });
    },
  });
}

export function useMarkAllAsRead() {
  const queryClient = useQueryClient();
  const { notifications } = useDataProvider();
  const qk = useQueryKeyPrefix();
  return useMutation({
    mutationFn: () => notifications.markAllAsRead(),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: qk('notifications') });
      queryClient.invalidateQueries({ queryKey: qk('notifications', 'unread-count') });
    },
  });
}
