import request from '@/utils/request'
import type { ApiResult, PageResult } from '@/api'
import type { Notification, NotificationParam, UnreadCountResult } from './model'
import { APP_API_URL } from '@/config/setting'

const BASE = APP_API_URL + '/notification'

/** 分页查询通知列表 */
export async function pageNotification(params: NotificationParam) {
  const res = await request.get<ApiResult<PageResult<Notification>>>(BASE + '/page', { params })
  if (res.data.code === 0) return res.data.data
  return Promise.reject(new Error(res.data.message))
}

/** 查询最近通知（用于铃铛下拉，最多 20 条） */
export async function listRecentNotification(params?: { type?: string; limit?: number }) {
  const res = await request.get<ApiResult<Notification[]>>(BASE + '/recent', { params })
  if (res.data.code === 0 && res.data.data) return res.data.data
  return Promise.reject(new Error(res.data.message))
}

/** 获取未读数量统计 */
export async function getUnreadCount() {
  const res = await request.get<ApiResult<UnreadCountResult>>(BASE + '/unread-count')
  if (res.data.code === 0 && res.data.data) return res.data.data
  return Promise.reject(new Error(res.data.message))
}

/** 标记单条通知为已读 */
export async function markRead(id: number) {
  const res = await request.put<ApiResult<unknown>>(BASE + `/read/${id}`)
  if (res.data.code === 0) return res.data.message
  return Promise.reject(new Error(res.data.message))
}

/** 标记全部已读 */
export async function markAllRead(data?: { type?: string }) {
  const res = await request.put<ApiResult<unknown>>(BASE + '/read-all', data)
  if (res.data.code === 0) return res.data.message
  return Promise.reject(new Error(res.data.message))
}

/** 删除单条通知 */
export async function removeNotification(id: number) {
  const res = await request.delete<ApiResult<unknown>>(BASE + '/' + id)
  if (res.data.code === 0) return res.data.message
  return Promise.reject(new Error(res.data.message))
}

/** 清空全部已读通知 */
export async function clearReadNotifications(data?: { type?: string }) {
  const res = await request.delete<ApiResult<unknown>>(BASE + '/clear-read', { data })
  if (res.data.code === 0) return res.data.message
  return Promise.reject(new Error(res.data.message))
}
