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

const BASE = APP_API_URL + '/app-credential'

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

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

/** 根据ID查询凭证 */
export async function getAppCredential(id: number) {
  const res = await request.get<ApiResult<AppCredential>>(BASE + '/' + id)
  if (res.data.code === 0 && res.data.data) return res.data.data
  return Promise.reject(new Error(res.data.message))
}

/** 创建凭证（自动生成 AppID/AppSecret，仅此次返回明文） */
export async function createAppCredential(data: AppCredential) {
  const res = await request.post<ApiResult<AppCredential>>(BASE, data)
  if (res.data.code === 0) return { message: res.data.message, data: res.data.data }
  return Promise.reject(new Error(res.data.message))
}

/** 修改凭证信息（不含密钥） */
export async function updateAppCredential(data: AppCredential) {
  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))
}

/** 重置 AppSecret */
export async function resetAppCredentialSecret(id: number) {
  const res = await request.post<ApiResult<AppCredential>>(BASE + '/resetSecret/' + id)
  if (res.data.code === 0) return { message: res.data.message, data: res.data.data }
  return Promise.reject(new Error(res.data.message))
}

/** 禁用/启用凭证 */
export async function updateAppCredentialStatus(id: number, status: number) {
  const res = await request.put<ApiResult<unknown>>(BASE + `/status/${id}/${status}`)
  if (res.data.code === 0) return res.data.message
  return Promise.reject(new Error(res.data.message))
}

/** 删除凭证 */
export async function removeAppCredential(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))
}
