// useMyNotifications：获取通知列表 + 标记已读
// 依据：02-architecture-design.md §4.2 GraphQL 接入、§14 通知偏好

"use client";

import { useQuery, useMutation } from "urql";
import {
  MY_NOTIFICATIONS,
  MARK_AS_READ,
  MARK_ALL_AS_READ,
} from "@/lib/graphql/operations";
import type { NotificationItem } from "@/types";

interface MyNotificationsResponse {
  myNotifications: NotificationItem[];
}

interface MarkAsReadResponse {
  markAsRead: { id: string; read: boolean };
}

interface MarkAllAsReadResponse {
  markAllAsRead: { count: number };
}

export function useMyNotifications(unreadOnly = false) {
  const [result] = useQuery<MyNotificationsResponse>({
    query: MY_NOTIFICATIONS,
    variables: { unreadOnly, limit: 50 },
  });

  const [, markAsReadMutation] = useMutation<MarkAsReadResponse>(MARK_AS_READ);
  const [, markAllAsReadMutation] =
    useMutation<MarkAllAsReadResponse>(MARK_ALL_AS_READ);

  async function markAsRead(notificationId: string) {
    return markAsReadMutation({ notificationId });
  }

  async function markAllAsRead() {
    return markAllAsReadMutation({});
  }

  return {
    notifications: result.data?.myNotifications ?? [],
    loading: result.fetching,
    error: result.error,
    markAsRead,
    markAllAsRead,
  };
}
