import request from '@/utils/request'
import type { ApiResult, PageResult } from '@/api'
import type { AppEvent, AppEventParam } from './model'
import {APP_API_URL} from '@/config/setting'

const BASE = APP_API_URL + '/app-event'

/** 分页查询动态 */
export async function pageAppEvent(params: AppEventParam) {
  const res = await request.get<ApiResult<PageResult<AppEvent>>>(BASE + '/page', { params })
  if (res.data.code === 0) return res.data.data
  return Promise.reject(new Error(res.data.message))
}

/** 查询全部动态 */
export async function listAppEvent(params?: AppEventParam) {
  const res = await request.get<ApiResult<AppEvent[]>>(BASE, { params })
  if (res.data.code === 0 && res.data.data) return res.data.data
  return Promise.reject(new Error(res.data.message))
}

/** 获取应用最新一条动态 */
export async function getLatestAppEvent(productId: number) {
  const res = await request.get<ApiResult<AppEvent>>(BASE + '/latest/' + productId)
  if (res.data.code === 0) return res.data.data
  return Promise.reject(new Error(res.data.message))
}

/** 记录一条操作动态（静默：失败不抛出） */
export async function addAppEvent(data: AppEvent): Promise<void> {
  try {
    await request.post<ApiResult<unknown>>(BASE, data)
  } catch {
    // 动态记录失败不影响主流程，静默处理
  }
}

/** 清空应用所有动态 */
export async function clearAppEvents(productId: number) {
  const res = await request.delete<ApiResult<unknown>>(BASE + '/clear/' + productId)
  if (res.data.code === 0) return res.data.message
  return Promise.reject(new Error(res.data.message))
}
