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

export interface MessageRecord {
  id: number
  type: string
  title: string
  subTitle: string
  avatar?: string
  content: string
  time: string
  status: 0 | 1
  messageType?: number
  deliveryStatus?: string
  channelType?: string
  attemptCount?: number
  lastError?: string
  incidentId?: number
  alertRecordId?: number
  nextRetryAt?: string
}
export type MessageListType = MessageRecord[]

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

/** 通知投递历史 */
export interface NotificationDeliveryRecord {
  id: number
  incident_id: number
  alert_record_id: number
  channel_id: number
  channel_type: string
  target: string
  subject: string
  content: string
  status: string
  attempt_count: number
  next_retry_at?: string
  last_error?: string
  trace_id?: string
  delivered_at?: string
  created_at?: string
  updated_at?: string
}

/** 投递历史查询参数 */
export interface NotificationDeliveryQuery {
  page?: number
  page_size?: number
  keyword?: string
  incident_id?: number
  status?: string
  channel_type?: string
}

/** 分页结果 */
export interface PageResult<T> {
  total: number
  page: number
  page_size: number
  data: T[]
}

function unwrapData<T>(response: ApiResponse<T> | T): T {
  const wrapped = response as ApiResponse<T>
  return (wrapped.details ?? wrapped.data ?? response) as T
}

/** 查询站内消息列表 */
export async function queryMessageList() {
  const response = await request.get<ApiResponse<MessageListType>>('/Alert/v1/message/list')
  return { data: unwrapData<MessageListType>(response) || [] }
}

interface MessageStatus {
  ids: number[]
}

/** 标记站内消息已读 */
export function setMessageStatus(data: MessageStatus) {
  return request.post<ApiResponse<boolean>>('/Alert/v1/message/read', data)
}

/** 查询通知投递历史 */
export function queryNotificationDeliveryHistory(params?: NotificationDeliveryQuery) {
  return request.get<ApiResponse<PageResult<NotificationDeliveryRecord>>>('/Alert/v1/notification/deliveries', { params: params || {} })
}

/** 人工补发通知 */
export function resendNotificationDelivery(id: number) {
  return request.post<ApiResponse<{ delivery_id: number; status: string }>>(`/Alert/v1/notification/deliveries/${id}/resend`)
}

export interface ChatRecord {
  id: number
  username: string
  content: string
  time: string
  isCollect: boolean
}

export function queryChatList() {
  return axios.post<ChatRecord[]>('/api/chat/list')
}
