import { callCloud, canUseCloud } from './cloud'
import { mockActiveUsers, mockConversations } from './mock'
import type { ActiveUser, ChatMessage, ChatPeer, Conversation, MessageTab } from '@/types/domain'

export async function getMessages(tab: MessageTab): Promise<{
  activeUsers: ActiveUser[]
  conversations: Conversation[]
}> {
  // Sample data only in non-cloud previews (e.g. H5 dev).
  if (!canUseCloud()) {
    const conversations =
      tab === 'unread'
        ? mockConversations.filter(item => item.unreadCount > 0)
        : mockConversations

    return { activeUsers: mockActiveUsers, conversations }
  }

  // Real mini program: always reflect cloud data, even when empty.
  try {
    return await callCloud('messageList', { tab })
  } catch {
    return { activeUsers: [], conversations: [] }
  }
}

export async function markConversationRead(conversationId: string): Promise<number> {
  if (!canUseCloud()) return 0
  const result = await callCloud<object, { unreadCount: number }>('conversationRead', { conversationId })
  return result.unreadCount
}

export async function sendMessage(
  content: string,
  options: { conversationId?: string; toOpenid?: string; toUserId?: string; msgType?: string }
): Promise<{ messageId: string; conversationId: string }> {
  if (!canUseCloud()) return { messageId: `local_${Date.now()}`, conversationId: options.conversationId || 'local' }
  return callCloud('messageSend', { content, ...options })
}

export async function getThread(params: {
  conversationId?: string
  targetUserId?: string
}): Promise<{ conversationId: string; peer: ChatPeer | null; messages: ChatMessage[] }> {
  if (!canUseCloud()) return { conversationId: params.conversationId || '', peer: null, messages: [] }
  try {
    return await callCloud('messageThread', params)
  } catch {
    return { conversationId: params.conversationId || '', peer: null, messages: [] }
  }
}
