/**
 * 通知管理 React Query Hooks
 *
 * 封装通知 CRUD 的数据获取与变更操作。
 * - useNotifications: 获取通知列表（支持类型筛选 + 分页）
 * - useCreateNotification: 创建通知（成功后自动刷新列表）
 * - useUpdateNotification: 更新通知（成功后自动刷新列表）
 * - useDeleteNotification: 删除通知（成功后自动刷新列表）
 */
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { notificationsApi } from '../api/notifications.api';
import type { NotificationListParams, CreateNotificationDto, UpdateNotificationDto } from '../api/notifications.api';
import { useToast } from '@/lib/hooks/use-toast';

/** 查询通知列表 */
export function useNotifications(params: NotificationListParams = {}) {
  return useQuery({
    queryKey: ['notifications', params],
    queryFn: () => notificationsApi.getList(params),
  });
}

/** 创建通知，成功后 invalidate 列表缓存并提示 */
export function useCreateNotification() {
  const queryClient = useQueryClient();
  const { toast } = useToast();

  return useMutation({
    mutationFn: (dto: CreateNotificationDto) => notificationsApi.create(dto),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['notifications'] });
      toast({ title: '通知创建成功', variant: 'success' as any });
    },
    onError: (error: any) => {
      toast({
        title: '创建失败',
        description: error?.response?.data?.message || '请稍后重试',
        variant: 'destructive',
      });
    },
  });
}

/** 更新通知，成功后 invalidate 列表缓存并提示 */
export function useUpdateNotification() {
  const queryClient = useQueryClient();
  const { toast } = useToast();

  return useMutation({
    mutationFn: ({ id, dto }: { id: string; dto: UpdateNotificationDto }) =>
      notificationsApi.update(id, dto),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['notifications'] });
      toast({ title: '通知更新成功', variant: 'success' as any });
    },
    onError: (error: any) => {
      toast({
        title: '更新失败',
        description: error?.response?.data?.message || '请稍后重试',
        variant: 'destructive',
      });
    },
  });
}

/** 删除通知，成功后 invalidate 列表缓存并提示 */
export function useDeleteNotification() {
  const queryClient = useQueryClient();
  const { toast } = useToast();

  return useMutation({
    mutationFn: (id: string) => notificationsApi.delete(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['notifications'] });
      toast({ title: '通知已删除', variant: 'success' as any });
    },
    onError: (error: any) => {
      toast({
        title: '删除失败',
        description: error?.response?.data?.message || '请稍后重试',
        variant: 'destructive',
      });
    },
  });
}
