import { request } from '@/api/request'

const logsHost = (import.meta.env.VITE_API_BASE_URL || '').replace(/\/+$/, '')
const BASE = logsHost ? `${logsHost}/Logs/v1` : '/Logs/v1'

/** 解析 bsm-sdk 风格响应，取出业务 data */
export function unwrapLogsPayload(res: any): any {
  if (res == null) return null
  if (typeof res.code === 'number' && res.code !== 0) return null
  return res.details ?? res.data ?? null
}

export interface LogEvent {
  id: number
  created_at: string
  source_kind: string
  remote_addr: string
  source_ip: string
  raw_payload: string
  normalized_summary: string
  normalized_detail: string
  device_name: string
  resource_type: string
  resource_id: string
  resource_name: string
  match_method: string
  severity_code: string
  trap_oid: string
  alert_sent: boolean
  dispatch_status: string
}

export interface LogEntriesParams {
  page?: number
  page_size?: number
  source_kind?: string
  resource_type?: string
  resource_id?: string
  dispatch_status?: string
  log_event_id?: number
}

export interface LogEntriesResult {
  total: number
  page: number
  page_size: number
  items: LogEvent[]
}

export interface AlertOutbox {
  id: number
  created_at: string
  updated_at: string
  log_event_id: number
  payload_json: string
  status: string
  retry_count: number
  next_retry_at: string
  last_error: string
}

export interface AlertOutboxParams {
  page?: number
  page_size?: number
  status?: string
}

export interface SyslogRule {
  id?: number
  created_at?: string
  updated_at?: string
  name: string
  enabled: boolean
  priority: number
  device_name_contains: string
  keyword_regex: string
  source_match: string
  message_regex: string
  recovery_match_regex: string
  lifecycle_key: string
  alert_name: string
  severity_code: string
  severity_mapping_json: string
  resource_uid_extract_regex: string
  policy_id: number
}

export interface TrapRule {
  id?: number
  created_at?: string
  updated_at?: string
  name: string
  enabled: boolean
  priority: number
  oid_prefix: string
  varbind_match_regex: string
  recovery_match_regex: string
  lifecycle_key: string
  alert_name: string
  severity_code: string
  policy_id: number
}

export interface TrapDictionaryEntry {
  id?: number
  created_at?: string
  updated_at?: string
  oid_prefix: string
  vendor: string
  oid: string
  name: string
  title: string
  description: string
  severity_code: string
  severity_mapping_json: string
  parse_expression: string
  recovery_message: string
  enabled: boolean
}

export interface TrapShield {
  id?: number
  created_at?: string
  updated_at?: string
  name: string
  enabled: boolean
  source_ip_cidr: string
  oid_prefix: string
  interface_hint: string
  time_windows_json: string
}

export interface AuditLog {
  id: number
  created_at: string
  trace_id: string
  source_service: string
  actor_id: string
  actor_name: string
  action: string
  object_type: string
  object_id: string
  operation_risk: string
  approval_id: string
  request_method: string
  request_path: string
  client_ip: string
  before_json: string
  after_json: string
  result: string
  error_message: string
}

export interface AuditLogParams {
  page?: number
  page_size?: number
  source_service?: string
  actor_id?: string
  action?: string
  object_type?: string
  object_id?: string
  operation_risk?: string
  result?: string
}

export interface DangerousApproval {
  id: number
  created_at: string
  updated_at: string
  request_id: string
  source_service: string
  action: string
  object_type: string
  object_id: string
  requester_id: string
  requester_name: string
  reason: string
  before_json: string
  after_json: string
  status: string
  reviewer_id: string
  reviewer_name: string
  review_comment: string
  reviewed_at: string
}

export interface ApprovalParams {
  page?: number
  page_size?: number
  source_service?: string
  status?: string
  requester_id?: string
  object_type?: string
}

export function fetchLogEntries(params?: LogEntriesParams) {
  return request.get(`${BASE}/entries`, { params })
}

export function fetchAlertOutbox(params?: AlertOutboxParams) {
  return request.get(`${BASE}/alert-outbox`, { params })
}

export function retryAlertOutbox(id: number) {
  return request.post(`${BASE}/alert-outbox/${id}/retry`)
}

export function replayLogEntry(id: number) {
  return request.post(`${BASE}/entries/${id}/replay`)
}

export function fetchSyslogRules() {
  return request.get(`${BASE}/syslog-rules`)
}

export function createSyslogRule(data: Partial<SyslogRule>) {
  return request.post(`${BASE}/syslog-rules`, data)
}

export function updateSyslogRule(id: number, data: Partial<SyslogRule>) {
  return request.put(`${BASE}/syslog-rules/${id}`, data)
}

export function deleteSyslogRule(id: number) {
  return request.delete(`${BASE}/syslog-rules/${id}`)
}

export function fetchTrapRules() {
  return request.get(`${BASE}/trap-rules`)
}

export function createTrapRule(data: Partial<TrapRule>) {
  return request.post(`${BASE}/trap-rules`, data)
}

export function updateTrapRule(id: number, data: Partial<TrapRule>) {
  return request.put(`${BASE}/trap-rules/${id}`, data)
}

export function deleteTrapRule(id: number) {
  return request.delete(`${BASE}/trap-rules/${id}`)
}

export function fetchTrapDictionary() {
  return request.get(`${BASE}/trap-dictionary`)
}

export function createTrapDictionary(data: Partial<TrapDictionaryEntry>) {
  return request.post(`${BASE}/trap-dictionary`, data)
}

export function updateTrapDictionary(id: number, data: Partial<TrapDictionaryEntry>) {
  return request.put(`${BASE}/trap-dictionary/${id}`, data)
}

export function deleteTrapDictionary(id: number) {
  return request.delete(`${BASE}/trap-dictionary/${id}`)
}

export function fetchTrapSuppressions() {
  return request.get(`${BASE}/trap-suppressions`)
}

export function createTrapSuppression(data: Partial<TrapShield>) {
  return request.post(`${BASE}/trap-suppressions`, data)
}

export function updateTrapSuppression(id: number, data: Partial<TrapShield>) {
  return request.put(`${BASE}/trap-suppressions/${id}`, data)
}

export function deleteTrapSuppression(id: number) {
  return request.delete(`${BASE}/trap-suppressions/${id}`)
}

export function fetchAuditLogs(params?: AuditLogParams) {
  return request.get(`${BASE}/audit/logs`, { params })
}

export function fetchDangerousApprovals(params?: ApprovalParams) {
  return request.get(`${BASE}/audit/approvals`, { params })
}

export function createDangerousApproval(data: Partial<DangerousApproval>) {
  return request.post(`${BASE}/audit/approvals`, data)
}

export function approveDangerousApproval(id: number, data: { reviewer_id: string; reviewer_name?: string; review_comment?: string }) {
  return request.post(`${BASE}/audit/approvals/${id}/approve`, data)
}

export function rejectDangerousApproval(id: number, data: { reviewer_id: string; reviewer_name?: string; review_comment?: string }) {
  return request.post(`${BASE}/audit/approvals/${id}/reject`, data)
}
