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

const BASE = APP_API_URL + '/article-category'

function isSuccess(code?: number) {
  return code === 0 || code === 200
}

export async function pageAppArticleCategory(params: AppArticleCategoryParam) {
  const res = await request.get<ApiResult<PageResult<AppArticleCategory>>>(BASE + '/page', { params })
  if (isSuccess(res.data.code)) return res.data.data
  return Promise.reject(new Error(res.data.message))
}

export async function listAppArticleCategory(params?: AppArticleCategoryParam) {
  const res = await request.get<ApiResult<AppArticleCategory[]>>(BASE, { params })
  if (isSuccess(res.data.code) && res.data.data) return res.data.data
  return Promise.reject(new Error(res.data.message))
}

export async function addAppArticleCategory(data: AppArticleCategory) {
  const res = await request.post<ApiResult<unknown>>(BASE, data)
  if (isSuccess(res.data.code)) return res.data.message
  return Promise.reject(new Error(res.data.message))
}

export async function updateAppArticleCategory(data: AppArticleCategory) {
  const res = await request.put<ApiResult<unknown>>(BASE, data)
  if (isSuccess(res.data.code)) return res.data.message
  return Promise.reject(new Error(res.data.message))
}

export async function removeAppArticleCategory(id?: number) {
  const res = await request.delete<ApiResult<unknown>>(BASE + '/' + id)
  if (isSuccess(res.data.code)) return res.data.message
  return Promise.reject(new Error(res.data.message))
}

export async function getAppArticleCategory(id: number) {
  const res = await request.get<ApiResult<AppArticleCategory>>(BASE + '/' + id)
  if (isSuccess(res.data.code) && res.data.data) return res.data.data
  return Promise.reject(new Error(res.data.message))
}
