import { callCloud, canUseCloud } from './cloud'
import { mockPosts } from './mock'
import type { FeedChannel, Post, PostComment } from '@/types/domain'

export async function getUserPosts(authorId?: string): Promise<Post[]> {
  if (!canUseCloud()) return mockPosts
  const result = await callCloud<object, { list: Post[] }>('userPosts', authorId ? { authorId } : {})
  return result.list || []
}

export async function getPostDetail(
  postId: string
): Promise<{ post: Post | null; comments: PostComment[] }> {
  if (!canUseCloud()) {
    return { post: mockPosts.find(item => item._id === postId) || null, comments: [] }
  }
  const result = await callCloud<{ postId: string }, { post: Post | null; comments: PostComment[] }>(
    'postDetail',
    { postId }
  )
  return { post: result.post || null, comments: result.comments || [] }
}

export async function getFeedList(channel: FeedChannel, topic?: string): Promise<Post[]> {
  // Only fall back to sample posts in non-cloud previews (e.g. H5 dev).
  if (!canUseCloud()) return mockPosts
  // In the real mini program always return cloud data — never mask it with
  // sample posts, even when the feed is empty or the call fails.
  const result = await callCloud<object, { list: Post[] }>('feedList', { channel, topic })
  return result.list || []
}

export async function setPostLike(postId: string, liked: boolean): Promise<{ liked: boolean; likes: number }> {
  if (!canUseCloud()) {
    const post = mockPosts.find(item => item._id === postId)
    return { liked, likes: Math.max(0, (post?.counts.likes || 0) + (liked ? 1 : -1)) }
  }

  return callCloud('postLike', { postId, liked })
}

export async function setPostFavorite(
  postId: string,
  favorited: boolean
): Promise<{ favorited: boolean; favorites: number }> {
  if (!canUseCloud()) return { favorited, favorites: 0 }
  return callCloud('postFavorite', { postId, favorited })
}

export async function createPostComment(postId: string, content: string): Promise<{ commentId: string; comments: number }> {
  if (!canUseCloud()) {
    const post = mockPosts.find(item => item._id === postId)
    return { commentId: `local_comment_${Date.now()}`, comments: (post?.counts.comments || 0) + 1 }
  }

  return callCloud('commentCreate', { postId, content })
}
