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

/**
 * 在线客服（用户端）
 *
 * 后端契约：com.snack.server.module.chat.controller.ChatUserController
 *   POST  /api/chat/session            → ChatSessionDetail  创建/恢复会话
 *   GET   /api/chat/sessions           → ChatSessionVO[]    我的会话列表
 *   GET   /api/chat/session/{id}       → ChatSessionDetail
 *   GET   /api/chat/session/{id}/messages?afterSeq&limit → ChatMessageVO[]
 *   POST  /api/chat/session/{id}/message                 → ChatMessageVO（HTTP 兜底）
 *   PUT   /api/chat/session/{id}/close                   → Void
 *   POST  /api/chat/heartbeat                            → Void
 */

/** 会话（对应后端 ChatSessionVO） */
export interface ChatSessionVO {
  id: number
  sessionNo: string
  userId: number
  username?: string
  nickname?: string
  avatar?: string
  adminId?: number
  adminName?: string
  status: 0 | 1 | 2 | 3
  statusText?: string
  unreadCount: number
  lastMessage?: string
  lastTime?: string
  createTime: string
}

/** 会话详情（含两端已确认序号） */
export interface ChatSessionDetail {
  session: ChatSessionVO
  userSeq: number
  adminSeq: number
  closeTime?: string
}

/** 消息（对应后端 ChatMessageVO） */
export interface ChatMessage {
  id: number
  sessionId: number
  seq: number
  senderId: number
  senderType: 0 | 1 | 2
  type: 'text' | 'image' | 'file' | 'product' | 'system'
  content: string
  extra?: string
  isRecalled: 0 | 1
  createTime: string
  /** 客户端消息 ID（WebSocket 回执去重用） */
  clientMsgId?: string
}

export function createOrRestoreSessionApi() {
  return request<ChatSessionDetail>({
    url: '/api/chat/session',
    method: 'POST'
  })
}

export function getMySessionsApi() {
  return request<ChatSessionVO[]>({
    url: '/api/chat/sessions',
    method: 'GET'
  })
}

export function getChatSessionDetailApi(id: number) {
  return request<ChatSessionDetail>({
    url: `/api/chat/session/${id}`,
    method: 'GET'
  })
}

export function getChatMessagesApi(
  sessionId: number,
  params: { afterSeq?: number; limit?: number } = {}
) {
  return request<ChatMessage[]>({
    url: `/api/chat/session/${sessionId}/messages`,
    method: 'GET',
    params
  })
}

export function sendChatMessageApi(
  sessionId: number,
  data: { type?: string; content: string; extra?: string; clientMsgId?: string }
) {
  return request<ChatMessage>({
    url: `/api/chat/session/${sessionId}/message`,
    method: 'POST',
    data
  })
}

export function closeChatSessionApi(sessionId: number) {
  return request<void>({
    url: `/api/chat/session/${sessionId}/close`,
    method: 'PUT'
  })
}

export function chatHeartbeatApi() {
  return request<void>({
    url: '/api/chat/heartbeat',
    method: 'POST'
  })
}
