import { GroupMemberResponse, UserDTO } from '../types/dto';
import { getUserCache } from '../services/database';
import { userManager } from './userManager';

/**
 * 为群成员列表补全用户资料（昵称、头像、用户名）。
 * cursor 接口仅返回 user_id 时，通过本地缓存和用户接口回填。
 */
export async function enrichGroupMembersWithUserProfiles(
  members: GroupMemberResponse[]
): Promise<GroupMemberResponse[]> {
  if (!Array.isArray(members) || members.length === 0) {
    return [];
  }

  const userIds = [...new Set(members.map((member) => String(member.user_id)))];
  const userMap = new Map<string, UserDTO>();

  await Promise.all(
    userIds.map(async (userId) => {
      try {
        const cachedUser = await getUserCache(userId);
        if (cachedUser) {
          userMap.set(userId, cachedUser);
          return;
        }

        const fetchedUser = await userManager.getUserById(userId);
        if (fetchedUser) {
          userMap.set(userId, fetchedUser);
        }
      } catch (error) {
        console.error('补全群成员用户资料失败:', error);
      }
    })
  );

  return members.map((member) => {
    if (member.user?.nickname || member.user?.username) {
      return member;
    }
    const user = userMap.get(String(member.user_id));
    return user ? { ...member, user } : member;
  });
}

