/**
 * 系统配置服务
 */

import { authFetch, baseUrl } from './authHelper'

export interface SystemConfig {
  id: number
  configKey: string
  configValue: string
  valueType: ValueType
  description?: string
  category: ConfigCategory
  isSystem: boolean
  createdAt?: string
  updatedAt?: string
}

export type ValueType = 'STRING' | 'NUMBER' | 'BOOLEAN' | 'JSON'

export type ConfigCategory = 'SYSTEM' | 'ACTIVITY' | 'REWARD' | 'NOTIFICATION' | 'SECURITY'

export interface ApiResponse<T> {
  code: number
  data: T
  message?: string
}

class SystemConfigService {
  private baseUrl = baseUrl || '/api/v1'

  /**
   * 获取系统配置列表
   */
  async getConfigs(params?: {
    category?: ConfigCategory
    keyword?: string
  }): Promise<SystemConfig[]> {
    const searchParams = new URLSearchParams()
    if (params?.category) searchParams.set('category', params.category)
    if (params?.keyword) searchParams.set('keyword', params.keyword)

    const response = await authFetch(`${this.baseUrl}/system/configs?${searchParams}`, {
      credentials: undefined
    })
    const result = await response.json() as ApiResponse<SystemConfig[]>
    if (result.code !== 200) {
      throw new Error(result.message || '获取配置列表失败')
    }
    return result.data
  }

  /**
   * 获取单个配置
   */
  async getConfigByKey(key: string): Promise<SystemConfig | null> {
    const response = await authFetch(`${this.baseUrl}/system/configs/${key}`, {
      credentials: undefined
    })
    const result = await response.json() as ApiResponse<SystemConfig>
    if (result.code !== 200) {
      return null
    }
    return result.data
  }

  /**
   * 更新配置
   */
  async updateConfig(key: string, value: string): Promise<void> {
    const response = await authFetch(`${this.baseUrl}/system/configs/${key}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      credentials: undefined,
      body: JSON.stringify({ value: value })
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '更新配置失败')
    }
  }

  /**
   * 批量更新配置
   */
  async batchUpdateConfigs(configs: { key: string; value: string }[]): Promise<void> {
    const response = await authFetch(`${this.baseUrl}/system/configs/batch`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      credentials: undefined,
      body: JSON.stringify({ configs })
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '批量更新配置失败')
    }
  }

  /**
   * 重置配置
   */
  async resetConfig(key: string): Promise<void> {
    const response = await authFetch(`${this.baseUrl}/system/configs/${key}/reset`, {
      method: 'POST',
      credentials: undefined
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '重置配置失败')
    }
  }

  /**
   * 清除缓存
   */
  async clearCache(cacheType?: string): Promise<void> {
    const url = cacheType
      ? `${this.baseUrl}/system/cache/clear?type=${cacheType}`
      : `${this.baseUrl}/system/cache/clear`
    const response = await authFetch(url, {
      method: 'POST',
      credentials: undefined
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '清除缓存失败')
    }
  }

  /**
   * 获取缓存列表
   */
  async getCacheList(): Promise<{ name: string; size: number }[]> {
    const response = await authFetch(`${this.baseUrl}/system/cache/list`, {
      credentials: undefined
    })
    const result = await response.json() as ApiResponse<any[]>
    if (result.code !== 200) {
      return []
    }
    return result.data
  }

  /**
   * 获取系统信息
   */
  async getSystemInfo(): Promise<{
    version: string
    uptime: number
    memory: { total: number; used: number; free: number }
    cpu: number
    threads: number
  }> {
    const response = await authFetch(`${this.baseUrl}/system/info`, {
      credentials: undefined
    })
    const result = await response.json() as ApiResponse<any>
    if (result.code !== 200) {
      throw new Error(result.message || '获取系统信息失败')
    }
    return result.data
  }

  // ========== API Key 管理 ==========

  /**
   * 获取API Key列表
   */
  async getApiKeys(): Promise<any[]> {
    const response = await authFetch(`${this.baseUrl}/keys`, {
      credentials: undefined
    })
    const result = await response.json() as ApiResponse<any[]>
    if (result.code !== 200) {
      throw new Error(result.message || '获取API密钥列表失败')
    }
    return result.data
  }

  /**
   * 创建API Key（提交审批）
   * 返回结构化审批结果，而非明文key
   */
  async createApiKey(name: string, activityId?: number): Promise<{
    apiKeyId: number
    recordId: number
    status: string
    message: string
  }> {
    const response = await authFetch(`${this.baseUrl}/keys`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: undefined,
      body: JSON.stringify({ name, activityId })
    })
    const result = await response.json() as ApiResponse<any>
    if (result.code !== 201 && result.code !== 200) {
      throw new Error(result.message || '创建API密钥失败')
    }
    // 后端返回结构化审批结果，不再返回明文key
    return {
      apiKeyId: result.data?.apiKeyId,
      recordId: result.data?.recordId,
      status: result.data?.status || 'PENDING_APPROVAL',
      message: result.data?.message || 'API Key已提交审批'
    }
  }

  /**
   * 删除API Key
   */
  async deleteApiKey(id: number): Promise<void> {
    const response = await authFetch(`${this.baseUrl}/keys/${id}`, {
      method: 'DELETE',
      credentials: undefined
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '删除API密钥失败')
    }
  }

  /**
   * 启用API Key
   */
  async enableApiKey(id: number): Promise<void> {
    const response = await authFetch(`${this.baseUrl}/keys/${id}/enable`, {
      method: 'POST',
      credentials: undefined
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '启用API密钥失败')
    }
  }

  /**
   * 禁用API Key
   */
  async disableApiKey(id: number): Promise<void> {
    const response = await authFetch(`${this.baseUrl}/keys/${id}/disable`, {
      method: 'POST',
      credentials: undefined
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '禁用API密钥失败')
    }
  }

  /**
   * 重置API Key
   */
  async resetApiKey(id: number): Promise<string> {
    const response = await authFetch(`${this.baseUrl}/keys/${id}/reset`, {
      method: 'POST',
      credentials: undefined
    })
    const result = await response.json() as ApiResponse<any>
    if (result.code !== 200) {
      throw new Error(result.message || '重置API密钥失败')
    }
    return result.data?.apiKey || result.data?.rawKey || ''
  }

  /**
   * 显示API Key（仅显示一次）
   */
  async revealApiKey(id: number): Promise<string> {
    const response = await authFetch(`${this.baseUrl}/keys/${id}/reveal`, {
      credentials: undefined
    })
    const result = await response.json() as ApiResponse<any>
    if (result.code !== 200) {
      throw new Error(result.message || '获取API密钥失败')
    }
    return result.data?.apiKey || ''
  }
}

export const systemConfigService = new SystemConfigService()
export default systemConfigService
