/**
 * 通知管理 API 模块
 *
 * 提供后台通知的 CRUD 操作接口，使用 apiClient 通过 Next.js rewrite
 * 代理到 mining-admin-service 的 /api/v2/notifications 端点。
 *
 * 后端响应格式: { success: boolean, data: T, timestamp: string }
 * 前端统一通过 response.data.data 提取实际数据。
 */
import { apiClient } from '@/lib/api/client';

// ==================== 枚举类型（与后端 Prisma 枚举对应） ====================

/** 通知类型 */
export type NotificationType = 'SYSTEM' | 'ACTIVITY' | 'REWARD' | 'UPGRADE' | 'ANNOUNCEMENT';

/** 通知优先级 */
export type NotificationPriority = 'LOW' | 'NORMAL' | 'HIGH' | 'URGENT';

/** 目标用户类型: ALL=全部用户, SPECIFIC=指定用户 */
export type TargetType = 'ALL' | 'SPECIFIC';

// ==================== 数据类型 ====================

/** 通知列表项（后端 formatNotification 返回格式） */
export interface NotificationItem {
  id: string;
  title: string;
  content: string;
  type: NotificationType;
  priority: NotificationPriority;
  targetType: TargetType;
  imageUrl: string | null;
  linkUrl: string | null;
  isEnabled: boolean;
  requiresForceRead: boolean;
  publishedAt: string | null;
  expiresAt: string | null;
  createdAt: string;
  /** 指定目标配置（后端格式，仅 SPECIFIC 类型时有值） */
  targetConfig?: { accountSequences: string[] } | null;
}

/** 创建通知请求体 */
export interface CreateNotificationDto {
  title: string;
  content: string;
  type?: NotificationType;
  priority?: NotificationPriority;
  targetType?: TargetType;
  /** 指定用户账号序列号列表（targetType=SPECIFIC 时必填） */
  targetAccountSequences?: string[];
  imageUrl?: string;
  linkUrl?: string;
  isEnabled?: boolean;
  requiresForceRead?: boolean;
  publishedAt?: string;
  expiresAt?: string;
}

/** 更新通知请求体（所有字段可选） */
export type UpdateNotificationDto = Partial<CreateNotificationDto>;

/** 通知列表查询参数 */
export interface NotificationListParams {
  type?: NotificationType;
  limit?: number;
  offset?: number;
}

/** 通知列表响应 */
export interface NotificationListResponse {
  items: NotificationItem[];
  total: number;
}

// ==================== API 方法 ====================

export const notificationsApi = {
  /**
   * 获取通知列表（管理端）
   * GET /notifications?type=&limit=&offset=
   */
  getList: async (params: NotificationListParams = {}): Promise<NotificationListResponse> => {
    const response = await apiClient.get('/notifications', { params });
    const data = response.data.data || response.data;
    // 后端 findAll 返回 { notifications: [...], total: number }
    return {
      items: data.notifications || data.items || [],
      total: data.total || 0,
    };
  },

  /**
   * 获取通知详情
   * GET /notifications/:id
   */
  getById: async (id: string): Promise<NotificationItem> => {
    const response = await apiClient.get(`/notifications/${id}`);
    return response.data.data || response.data;
  },

  /**
   * 创建通知
   * POST /notifications
   * 前端 DTO 使用 targetAccountSequences，需转换为后端格式 targetConfig.accountSequences
   */
  create: async (dto: CreateNotificationDto): Promise<NotificationItem> => {
    const { targetAccountSequences, ...rest } = dto;
    const payload = {
      ...rest,
      ...(targetAccountSequences?.length && {
        targetConfig: { accountSequences: targetAccountSequences },
      }),
    };
    const response = await apiClient.post('/notifications', payload);
    return response.data.data || response.data;
  },

  /**
   * 更新通知
   * PUT /notifications/:id
   */
  update: async (id: string, dto: UpdateNotificationDto): Promise<NotificationItem> => {
    const { targetAccountSequences, ...rest } = dto;
    const payload = {
      ...rest,
      ...(targetAccountSequences !== undefined && {
        targetConfig: { accountSequences: targetAccountSequences || [] },
      }),
    };
    const response = await apiClient.put(`/notifications/${id}`, payload);
    return response.data.data || response.data;
  },

  /**
   * 删除通知
   * DELETE /notifications/:id
   */
  delete: async (id: string): Promise<void> => {
    await apiClient.delete(`/notifications/${id}`);
  },
};
