import { callCloud, canUseCloud } from './cloud'
import { resolveCloudFileUrlMap } from './cloud-file'
import { markStale } from '@/store/dataBus'
import type { FollowCounts, SocialUser } from '@/types/domain'

export type FollowListType = 'friends' | 'following' | 'followers'

const emptyCounts: FollowCounts = { following: 0, followers: 0, friends: 0 }

async function resolveSocialUserAssets(list: SocialUser[]): Promise<SocialUser[]> {
  const urlMap = await resolveCloudFileUrlMap(list.map(user => user.avatarUrl || ''))
  const readUrl = (url?: string) => {
    if (!url) return url
    return urlMap.has(url) ? urlMap.get(url) || '' : url
  }

  return list.map(user => ({ ...user, avatarUrl: readUrl(user.avatarUrl) }))
}

export async function getFollowList(type: FollowListType): Promise<{ list: SocialUser[]; counts: FollowCounts }> {
  if (!canUseCloud()) return { list: [], counts: emptyCounts }
  try {
    const result = await callCloud<object, { list: SocialUser[]; counts: FollowCounts }>('followList', { type })
    return { list: await resolveSocialUserAssets(result.list || []), counts: result.counts || emptyCounts }
  } catch {
    return { list: [], counts: emptyCounts }
  }
}

export async function discoverUsers(keyword?: string): Promise<SocialUser[]> {
  if (!canUseCloud()) return []
  try {
    const res = await callCloud<object, { list: SocialUser[] }>('userList', { keyword: keyword || '' })
    return resolveSocialUserAssets(res.list || [])
  } catch {
    return []
  }
}

export async function toggleFollow(targetUserId: string, follow: boolean): Promise<{ following: boolean; mutual: boolean }> {
  const result = canUseCloud()
    ? await callCloud<object, { following: boolean; mutual: boolean }>('followToggle', { targetUserId, follow })
    : { following: follow, mutual: false }
  markStale('profile')
  return result
}
