/**
 * 通知服务
 * 处理系统通知、互动通知等功能
 */

import { api, PaginatedData } from './api';
import { Notification, NotificationBadge, NotificationType } from '../types';
import { CursorPaginationRequest, CursorPaginationResponse } from '../types/dto';

// 通知列表响应
interface NotificationListResponse {
  list: Notification[];
  total: number;
  page: number;
  page_size: number;
  total_pages: number;
}

// 通知角标响应
interface NotificationBadgeResponse {
  total: number;
  likes: number;
  comments: number;
  follows: number;
  system: number;
}

// 通知响应
type NotificationResponse = Notification;

// 通知服务类
class NotificationService {
  // 获取通知列表
  async getNotifications(
    page = 1,
    pageSize = 20,
    type?: NotificationType
  ): Promise<PaginatedData<Notification>> {
    try {
      const params: Record<string, any> = {
        page,
        page_size: pageSize,
      };
      
      if (type) {
        params.type = type;
      }
      
      const response = await api.get<NotificationListResponse>('/notifications', params);
      return response.data;
    } catch (error) {
      console.error('获取通知列表失败:', error);
      return {
        list: [],
        total: 0,
        page: 1,
        page_size: pageSize,
        total_pages: 0,
      };
    }
  }

  // 获取未读通知数
  async getUnreadCount(): Promise<number> {
    try {
      const response = await api.get<{ count: number }>('/notifications/unread-count');
      return response.data.count || 0;
    } catch (error) {
      console.error('获取未读通知数失败:', error);
      return 0;
    }
  }

  // 获取通知角标
  async getNotificationBadge(): Promise<NotificationBadge> {
    try {
      const response = await api.get<NotificationBadgeResponse>('/notifications/badge');
      return {
        total: response.data.total || 0,
        likes: response.data.likes || 0,
        comments: response.data.comments || 0,
        follows: response.data.follows || 0,
        system: response.data.system || 0,
      };
    } catch (error) {
      console.error('获取通知角标失败:', error);
      return {
        total: 0,
        likes: 0,
        comments: 0,
        follows: 0,
        system: 0,
      };
    }
  }

  // 标记单个通知为已读
  async markAsRead(notificationId: string): Promise<boolean> {
    try {
      const response = await api.post(`/notifications/${notificationId}/read`);
      return response.code === 0;
    } catch (error) {
      console.error('标记通知为已读失败:', error);
      return false;
    }
  }

  // 标记所有通知为已读
  async markAllAsRead(): Promise<boolean> {
    try {
      const response = await api.post('/notifications/read-all');
      return response.code === 0;
    } catch (error) {
      console.error('标记所有通知为已读失败:', error);
      return false;
    }
  }

  // 删除通知
  async deleteNotification(notificationId: string): Promise<boolean> {
    try {
      const response = await api.delete(`/notifications/${notificationId}`);
      return response.code === 0;
    } catch (error) {
      console.error('删除通知失败:', error);
      return false;
    }
  }

  // 清空所有通知
  async clearAll(): Promise<boolean> {
    try {
      const response = await api.delete('/notifications');
      return response.code === 0;
    } catch (error) {
      console.error('清空通知失败:', error);
      return false;
    }
  }

  // 获取互动通知（点赞、评论、关注）
  async getInteractionNotifications(page = 1, pageSize = 20): Promise<PaginatedData<Notification>> {
    return this.getNotifications(page, pageSize, 'like_post');
  }

  // 获取系统通知
  async getSystemNotifications(page = 1, pageSize = 20): Promise<PaginatedData<Notification>> {
    return this.getNotifications(page, pageSize, 'system');
  }

  // 获取@我的通知
  async getMentionNotifications(page = 1, pageSize = 20): Promise<PaginatedData<Notification>> {
    return this.getNotifications(page, pageSize, 'mention');
  }

  // ==================== 游标分页方法 ====================

  /**
   * 获取通知列表（游标分页）
   * GET /api/v1/notifications/cursor
   * @param params 游标分页请求参数
   */
  async getNotificationsCursor(
    params: CursorPaginationRequest = {}
  ): Promise<CursorPaginationResponse<Notification>> {
    try {
      const response = await api.get<CursorPaginationResponse<Notification>>(
        '/notifications/cursor',
        params
      );
      return response.data;
    } catch (error) {
      console.error('获取通知列表失败:', error);
      return {
        list: [],
        next_cursor: null,
        prev_cursor: null,
        has_more: false,
      };
    }
  }
}

// 导出通知服务实例
export const notificationService = new NotificationService();
