import { apiClient } from '@/shared/api/client'
import type { ApiResponse } from '@/shared/types/types'

export interface PushChannel {
  id: number
  name: string
  type: 'bark' | 'wpush'
  config: Record<string, string>
  enabled: boolean
  created_at: string
  updated_at: string
}

export interface PushRule {
  id: number
  event: string
  enabled: boolean
  threshold: number
  message_template: string
  created_at: string
  updated_at: string
}

export interface CreateChannelPayload {
  name: string
  type: 'bark' | 'wpush'
  config: Record<string, string>
}

export interface UpdateChannelPayload {
  name?: string
  config?: Record<string, string>
  enabled?: boolean
}

export interface UpdateRulePayload {
  enabled?: boolean
  threshold?: number
  message_template?: string
}

// ── 渠道 ──

export async function fetchPushChannels() {
  const { data } = await apiClient.get<ApiResponse<{ items: PushChannel[] }>>('/admin/push-channels')
  return data.data.items
}

export async function createPushChannel(payload: CreateChannelPayload) {
  const { data } = await apiClient.post<ApiResponse<PushChannel>>('/admin/push-channels', payload)
  return data.data
}

export async function updatePushChannel(id: number, payload: UpdateChannelPayload) {
  const { data } = await apiClient.put<ApiResponse<PushChannel>>(`/admin/push-channels/${id}`, payload)
  return data.data
}

export async function deletePushChannel(id: number) {
  const { data } = await apiClient.delete<ApiResponse<{ deleted: boolean }>>(`/admin/push-channels/${id}`)
  return data.data
}

export async function testPushChannel(id: number) {
  const { data } = await apiClient.post<ApiResponse<{ sent: boolean }>>(`/admin/push-channels/${id}/test`)
  return data.data
}

// ── 规则 ──

export async function fetchPushRules() {
  const { data } = await apiClient.get<ApiResponse<{ items: PushRule[] }>>('/admin/push-rules')
  return data.data.items
}

export async function updatePushRule(id: number, payload: UpdateRulePayload) {
  const { data } = await apiClient.put<ApiResponse<PushRule>>(`/admin/push-rules/${id}`, payload)
  return data.data
}
