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

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 = '/api'

  /**
   * 获取系统配置列表
   */
  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 fetch(`${this.baseUrl}/system/configs?${searchParams}`, {
      credentials: 'include'
    })
    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 fetch(`${this.baseUrl}/system/configs/${key}`, {
      credentials: 'include'
    })
    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 fetch(`${this.baseUrl}/system/configs/${key}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      body: JSON.stringify({ configValue: 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 fetch(`${this.baseUrl}/system/configs/batch`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      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 fetch(`${this.baseUrl}/system/configs/${key}/reset`, {
      method: 'POST',
      credentials: 'include'
    })
    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 fetch(url, {
      method: 'POST',
      credentials: 'include'
    })
    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 fetch(`${this.baseUrl}/system/cache/list`, {
      credentials: 'include'
    })
    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 fetch(`${this.baseUrl}/system/info`, {
      credentials: 'include'
    })
    const result = await response.json() as ApiResponse<any>
    if (result.code !== 200) {
      throw new Error(result.message || '获取系统信息失败')
    }
    return result.data
  }
}

export const systemConfigService = new SystemConfigService()
export default systemConfigService
