import { getConfig } from '../core/config' import { apiRequest, getToken, saveToken } from '../core/http' import { ImClient } from './imClient' import type { ChatType, ImEventListener, ImMessage, MsgType } from './types' let client: ImClient | null = null export const ImSDK = { async login(userId: string, nickname?: string, avatar?: string): Promise { const config = getConfig() const res = await apiRequest<{ token: string }>('/api/im/auth/login', { method: 'POST', params: { appId: config.appId, userId, ...(nickname ? { nickname } : {}), ...(avatar ? { avatar } : {}), }, }) await saveToken(res.token) client = new ImClient(config.imWsUrl, res.token, config.appId) client.connect() }, async reconnect(): Promise { const config = getConfig() const token = await getToken() if (!token) throw new Error('ImSDK: token not found') client = new ImClient(config.imWsUrl, token, config.appId) client.connect() }, async fetchHistory(toId: string, page = 0, size = 20): Promise { const config = getConfig() const res = await apiRequest<{ content?: ImMessage[] } | ImMessage[]>(`/api/im/messages/history/${encodeURIComponent(toId)}`, { params: { appId: config.appId, page: String(page), size: String(size), }, }) return Array.isArray(res) ? res : (res.content ?? []) }, async sendMessage( toId: string, chatType: ChatType, msgType: MsgType, content: string, mentionedUserIds?: string, ): Promise { const config = getConfig() return apiRequest('/api/im/messages/send', { method: 'POST', params: { appId: config.appId }, body: { toId, chatType, msgType, content, mentionedUserIds: mentionedUserIds ?? '', }, }) }, async revokeMessage(messageId: string): Promise { const config = getConfig() return apiRequest(`/api/im/messages/${encodeURIComponent(messageId)}/revoke`, { method: 'POST', params: { appId: config.appId }, }) }, addListener(listener: ImEventListener) { client?.addListener(listener) }, removeListener(listener: ImEventListener) { client?.removeListener(listener) }, disconnect() { client?.disconnect() client = null }, subscribeGroup(groupId: string) { client?.subscribeGroup(groupId) }, isConnected() { return client?.isConnected() ?? false }, }