/**
 * 风险管理服务
 */

export interface RiskAlert {
  id: number
  type: RiskType
  level: RiskLevel
  title: string
  description: string
  userId?: number
  userName?: string
  activityId?: number
  activityName?: string
  data?: Record<string, any>
  status: AlertStatus
  handleResult?: string
  handledBy?: number
  handledAt?: string
  createdAt: string
  updatedAt?: string
}

export type RiskType = 'CHEAT' | 'ABNORMAL' | 'VIOLATION' | 'SYSTEM'

export type RiskLevel = 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL'

export type AlertStatus = 'PENDING' | 'HANDLED' | 'IGNORED' | 'WHITELISTED'

export interface RiskRule {
  id: number
  name: string
  code: string
  description?: string
  riskType: RiskType
  condition: string
  action: RiskAction
  status: RuleStatus
  priority: number
  createdBy?: number
  createdAt?: string
  updatedAt?: string
}

export type RiskAction = 'BLOCK' | 'WARN' | 'LOG' | 'CAPTCHA'

export type RuleStatus = 'ENABLED' | 'DISABLED'

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

class RiskService {
  private baseUrl = '/api'

  /**
   * 获取风险告警列表
   */
  async getAlerts(params?: {
    page?: number
    size?: number
    type?: string
    level?: string
    status?: string
    startDate?: string
    endDate?: string
  }): Promise<RiskAlert[]> {
    const searchParams = new URLSearchParams()
    if (params?.page) searchParams.set('page', String(params.page))
    if (params?.size) searchParams.set('size', String(params.size))
    if (params?.type) searchParams.set('type', params.type)
    if (params?.level) searchParams.set('level', params.level)
    if (params?.status) searchParams.set('status', params.status)

    const response = await fetch(`${this.baseUrl}/risk/alerts?${searchParams}`, {
      credentials: 'include'
    })
    const result = await response.json() as ApiResponse<RiskAlert[]>
    if (result.code !== 200) {
      throw new Error(result.message || '获取风险告警失败')
    }
    return result.data
  }

  /**
   * 获取单个告警详情
   */
  async getAlertById(id: number): Promise<RiskAlert | null> {
    const response = await fetch(`${this.baseUrl}/risk/alerts/${id}`, {
      credentials: 'include'
    })
    const result = await response.json() as ApiResponse<RiskAlert>
    if (result.code !== 200) {
      return null
    }
    return result.data
  }

  /**
   * 处理风险告警
   */
  async handleAlert(id: number, data: {
    status: AlertStatus
    handleResult: string
  }): Promise<void> {
    const response = await fetch(`${this.baseUrl}/risk/alerts/${id}/handle`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      body: JSON.stringify(data)
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '处理告警失败')
    }
  }

  /**
   * 批量处理告警
   */
  async batchHandleAlerts(ids: number[], data: {
    status: AlertStatus
    handleResult: string
  }): Promise<void> {
    const response = await fetch(`${this.baseUrl}/risk/alerts/batch-handle`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      body: JSON.stringify({ ids, ...data })
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '批量处理失败')
    }
  }

  /**
   * 获取风控规则列表
   */
  async getRules(params?: {
    page?: number
    size?: number
    riskType?: string
    status?: string
  }): Promise<RiskRule[]> {
    const searchParams = new URLSearchParams()
    if (params?.page) searchParams.set('page', String(params.page))
    if (params?.size) searchParams.set('size', String(params.size))
    if (params?.riskType) searchParams.set('riskType', params.riskType)
    if (params?.status) searchParams.set('status', params.status)

    const response = await fetch(`${this.baseUrl}/risk/rules?${searchParams}`, {
      credentials: 'include'
    })
    const result = await response.json() as ApiResponse<RiskRule[]>
    if (result.code !== 200) {
      throw new Error(result.message || '获取风控规则失败')
    }
    return result.data
  }

  /**
   * 创建风控规则
   */
  async createRule(data: Partial<RiskRule>): Promise<number> {
    const response = await fetch(`${this.baseUrl}/risk/rules`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      body: JSON.stringify(data)
    })
    const result = await response.json() as ApiResponse<number>
    if (result.code !== 200) {
      throw new Error(result.message || '创建规则失败')
    }
    return result.data
  }

  /**
   * 更新风控规则
   */
  async updateRule(id: number, data: Partial<RiskRule>): Promise<void> {
    const response = await fetch(`${this.baseUrl}/risk/rules/${id}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      body: JSON.stringify(data)
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '更新规则失败')
    }
  }

  /**
   * 删除风控规则
   */
  async deleteRule(id: number): Promise<void> {
    const response = await fetch(`${this.baseUrl}/risk/rules/${id}`, {
      method: 'DELETE',
      credentials: 'include'
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '删除规则失败')
    }
  }

  /**
   * 启用/禁用规则
   */
  async toggleRule(id: number, enabled: boolean): Promise<void> {
    const response = await fetch(`${this.baseUrl}/risk/rules/${id}/toggle`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      body: JSON.stringify({ enabled })
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '切换规则状态失败')
    }
  }

  /**
   * 获取待处理告警数量
   */
  async getPendingAlertCount(): Promise<number> {
    const response = await fetch(`${this.baseUrl}/risk/alerts/pending-count`, {
      credentials: 'include'
    })
    const result = await response.json() as ApiResponse<number>
    if (result.code !== 200) {
      return 0
    }
    return result.data
  }
}

export const riskService = new RiskService()
export default riskService
