import request from '@/utils/request'
import type { ApiResult, PageResult } from '@/api'
import type { AppCloudCredential, AppCloudCredentialParam } from './model'
import {
  CLOUD_PROVIDER_OPTIONS,
  getProviderLabel,
  getProviderIcon,
} from './model'

// 重新导出，保持向后兼容
export { CLOUD_PROVIDER_OPTIONS, getProviderLabel, getProviderIcon }

const BASE = '/api/app/cloud-credential'

/**
 * 分页查询云账号凭证
 */
export async function pageCloudCredential(params?: AppCloudCredentialParam) {
  const res = await request.get<ApiResult<PageResult<AppCloudCredential>>>(BASE + '/page', { params })
  if (res.data.code === 200 || res.data.code === 0) return res.data.data
  return Promise.reject(new Error(res.data.message))
}

/**
 * 查询用户全部云账号凭证
 */
export async function listCloudCredential(provider?: string) {
  const res = await request.get<ApiResult<AppCloudCredential[]>>(BASE, { params: { provider } })
  if ((res.data.code === 200 || res.data.code === 0) && res.data.data) return res.data.data
  return Promise.reject(new Error(res.data.message))
}

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

/**
 * 创建云账号凭证
 */
export async function createCloudCredential(data: AppCloudCredential) {
  const res = await request.post<ApiResult<AppCloudCredential>>(BASE, data)
  if (res.data.code === 200 || res.data.code === 0) return res.data.data
  return Promise.reject(new Error(res.data.message))
}

/**
 * 修改云账号凭证
 */
export async function updateCloudCredential(data: AppCloudCredential) {
  const res = await request.put<ApiResult<unknown>>(BASE, data)
  if (res.data.code === 200 || res.data.code === 0) return res.data.message
  return Promise.reject(new Error(res.data.message))
}

/**
 * 删除云账号凭证
 */
export async function removeCloudCredential(id: number) {
  const res = await request.delete<ApiResult<unknown>>(BASE + '/' + id)
  if (res.data.code === 200 || res.data.code === 0) return res.data.message
  return Promise.reject(new Error(res.data.message))
}

/**
 * 测试云账号凭证连接
 */
export async function testCloudCredential(id: number) {
  const res = await request.post<ApiResult<{ success: boolean; message: string }>>(BASE + '/test/' + id)
  if (res.data.code === 200 || res.data.code === 0) return res.data.data
  return Promise.reject(new Error(res.data.message))
}