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

const BASE = APP_API_URL + '/app-version'

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

/** 查询全部版本 */
export async function listAppVersion(params?: AppVersionParam) {
  const res = await request.get<ApiResult<AppVersion[]>>(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 getCurrentVersion(productId: number) {
  const res = await request.get<ApiResult<AppVersion>>(BASE + '/current/' + productId)
  if (res.data.code === 0) return res.data.data
  return Promise.reject(new Error(res.data.message))
}

/** 新增版本 */
export async function addAppVersion(data: AppVersion) {
  const res = await request.post<ApiResult<unknown>>(BASE, data)
  if (res.data.code === 0) return res.data.message
  return Promise.reject(new Error(res.data.message))
}

/** 修改版本 */
export async function updateAppVersion(data: AppVersion) {
  const res = await request.put<ApiResult<unknown>>(BASE, data)
  if (res.data.code === 0) return res.data.message
  return Promise.reject(new Error(res.data.message))
}

/** 发布版本 */
export async function publishAppVersion(id: number) {
  const res = await request.post<ApiResult<unknown>>(BASE + '/publish/' + id)
  if (res.data.code === 0) return res.data.message
  return Promise.reject(new Error(res.data.message))
}

/** 回滚到指定版本 */
export async function rollbackAppVersion(id: number) {
  const res = await request.post<ApiResult<unknown>>(BASE + '/rollback/' + id)
  if (res.data.code === 0) return res.data.message
  return Promise.reject(new Error(res.data.message))
}

/** 删除版本 */
export async function removeAppVersion(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))
}
