import { create } from 'zustand';
import type { AppNotification } from '../types';
import { notificationApi } from '../lib/api';

interface NotificationState {
  unreadCount: number;
  list: AppNotification[];
  total: number;
  page: number;
  pageSize: number;
  loading: boolean;
  fetchUnreadCount: () => Promise<void>;
  fetchList: (params?: { unread_only?: boolean; page?: number; page_size?: number }) => Promise<void>;
  markRead: (id: number) => Promise<void>;
  markAllRead: () => Promise<void>;
}

export const useNotificationStore = create<NotificationState>((set, get) => ({
  unreadCount: 0,
  list: [],
  total: 0,
  page: 1,
  pageSize: 20,
  loading: false,

  fetchUnreadCount: async () => {
    try {
      const { data } = await notificationApi.getUnreadCount();
      set({ unreadCount: data.unread_count });
    } catch {
      // 网络抖动/未登录都静默,保持当前值,不要把红点炸没
    }
  },

  fetchList: async (params) => {
    set({ loading: true });
    try {
      const { data } = await notificationApi.list(params);
      set({
        list: data.results,
        total: data.total,
        unreadCount: data.unread_count,
        page: data.page,
        pageSize: data.page_size,
        loading: false,
      });
    } catch {
      set({ loading: false });
    }
  },

  markRead: async (id) => {
    // 乐观更新:先动 UI 再发请求,失败回滚
    const prevList = get().list;
    const prevUnread = get().unreadCount;
    const target = prevList.find((n) => n.id === id);
    if (target && !target.is_read) {
      set({
        list: prevList.map((n) => (n.id === id ? { ...n, is_read: true } : n)),
        unreadCount: Math.max(0, prevUnread - 1),
      });
    }
    try {
      await notificationApi.markRead(id);
    } catch {
      // 回滚
      set({ list: prevList, unreadCount: prevUnread });
    }
  },

  markAllRead: async () => {
    const prevList = get().list;
    const prevUnread = get().unreadCount;
    set({
      list: prevList.map((n) => ({ ...n, is_read: true })),
      unreadCount: 0,
    });
    try {
      await notificationApi.markAllRead();
    } catch {
      set({ list: prevList, unreadCount: prevUnread });
    }
  },
}));
