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

const BASE = APP_API_URL + '/developer-resource'

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

/** 查询资源列表（不分页） */
export async function listAppResource(params?: AppResourceParam) {
  const res = await request.get<ApiResult<AppResource[]>>(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 getAppResource(resourceId: number) {
  const res = await request.get<ApiResult<AppResource>>(BASE + '/' + resourceId)
  if (res.data.code === 0) return res.data.data
  return Promise.reject(new Error(res.data.message))
}

/** 统计各类型资源数量 */
export async function statsAppResource(): Promise<Record<string, number>> {
  const res = await request.get<ApiResult<Record<string, number>>>(BASE + '/stats')
  if (res.data.code === 0) return res.data.data ?? {}
  return Promise.reject(new Error(res.data.message))
}

/** 新增资源 */
export async function addAppResource(data: AppResource) {
  const res = await request.post<ApiResult<AppResource>>(BASE, data)
  if (res.data.code === 0) return res.data.data
  return Promise.reject(new Error(res.data.message))
}

/** 修改资源 */
export async function updateAppResource(data: AppResource) {
  const res = await request.put<ApiResult<AppResource>>(BASE, data)
  if (res.data.code === 0) return res.data.data
  return Promise.reject(new Error(res.data.message))
}

/** 删除资源 */
export async function removeAppResource(resourceId: number, code?: string) {
  const res = await request.delete<ApiResult<unknown>>(BASE + '/' + resourceId, code ? { data: { code } } : {})
  if (res.data.code === 0) return res.data.message
  return Promise.reject(new Error(res.data.message))
}

/** 批量删除资源 */
export async function removeBatchAppResource(ids: number[]) {
  const res = await request.delete<ApiResult<unknown>>(BASE + '/batch', { data: ids })
  if (res.data.code === 0) return res.data.message
  return Promise.reject(new Error(res.data.message))
}

/** 测试数据库连接 */
export async function testConnection(params: { host: string; port?: number; dbType?: string; username: string; password: string; dbName?: string }) {
  const res = await request.post<ApiResult<{ success: boolean; message: string; detail?: string }>>(BASE + '/test-connection', params)
  if (res.data.code === 0) return res.data.data
  return Promise.reject(new Error(res.data.message))
}

/** 测试 SSH 连接 */
export async function testSshConnection(params: { host: string; port?: number; username: string; password: string }) {
  const res = await request.post<ApiResult<{ success: boolean; message: string; detail?: string }>>(BASE + '/test-ssh', params)
  if (res.data.code === 0) return res.data.data
  return Promise.reject(new Error(res.data.message))
}

/** 重试创建数据库 */
export async function retryCreateDatabase(resourceId: number) {
  const res = await request.post<ApiResult<unknown>>(BASE + '/retry-create-database/' + resourceId)
  if (res.data.code === 0) return res.data.message
  return Promise.reject(new Error(res.data.message))
}

/** 重置数据库密码 */
export async function resetDatabasePassword(resourceId: number) {
  const res = await request.post<ApiResult<{ password: string }>>(BASE + '/reset-password/' + resourceId)
  if (res.data.code === 200 || res.data.code === 0) return res.data.data
  return Promise.reject(new Error(res.data.message))
}

/** 刷新存储桶信息 */
export async function refreshStorage(resourceId: number) {
  const res = await request.post<ApiResult<{ usedBytes: number; objectCount: number }>>(BASE + '/refresh-storage/' + resourceId)
  if (res.data.code === 200 || res.data.code === 0) return res.data.data
  return Promise.reject(new Error(res.data.message))
}

/** 检查域名 DNS 状态 */
export async function checkDomainDns(resourceId: number) {
  const res = await request.post<ApiResult<{ status: 'ok' | 'error' | 'pending'; ip?: string; message?: string }>>(BASE + '/check-dns/' + resourceId)
  if (res.data.code === 200 || res.data.code === 0) return res.data.data
  return Promise.reject(new Error(res.data.message))
}

/** 生成 Nginx 配置 */
export async function generateNginxConfig(resourceId: number) {
  const res = await request.get<ApiResult<{ config: string }>>(BASE + '/nginx-config/' + resourceId)
  if (res.data.code === 200 || res.data.code === 0) return res.data.data
  return Promise.reject(new Error(res.data.message))
}

/** 获取域名统计信息 */
export async function getDomainStats() {
  const res = await request.get<ApiResult<{
    total: number
    icpCount: number
    sslCount: number
    expiringCount: number
    errorCount: number
  }>>(BASE + '/domain-stats')
  if (res.data.code === 200 || res.data.code === 0) return res.data.data
  return Promise.reject(new Error(res.data.message))
}

/** 批量导入域名 */
export async function importDomains(data: { domains: Array<Partial<AppResource>> }) {
  const res = await request.post<ApiResult<{ success: number; failed: number; errors: string[] }>>(BASE + '/import-domains', 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 exportDomains(params?: AppResourceParam) {
  const res = await request.get(BASE + '/export-domains', { params, responseType: 'blob' })
  return res.data
}

/** 获取1Panel服务器状态 */
export interface ServerStatus {
  cpu: string           // CPU 使用率 %
  memory: string        // 内存使用率 %
  memoryUsed: string    // 内存已用
  memoryTotal: string   // 内存总量
  disk: string          // 磁盘使用率 %
  diskUsed: string      // 磁盘已用
  diskTotal: string     // 磁盘总量
  load: string          // 系统负载
  uptime: string        // 运行时间
  online: number         // 在线状态 1=在线 0=离线
  message?: string      // 错误信息
}

export async function getServerStatus(resourceId: number): Promise<ServerStatus> {
  const res = await request.get<ApiResult<ServerStatus>>(BASE + '/server-status/' + resourceId)
  if (res.data.code === 200 || res.data.code === 0) return res.data.data!
  return Promise.reject(new Error(res.data.message))
}
