import { DataSource } from 'typeorm';
import { ServerEntity } from '../../../entities';
import { rowToServer } from '../../mappers';
import { loadServerRelationsMap } from '../../relations';
import { loadMembershipCounts, rankTrendingServers } from './server-ranking.util';

const DEFAULT_LIMIT = 12;

export async function handleGetTrendingServers(dataSource: DataSource, limit = DEFAULT_LIMIT) {
  const rows = await dataSource.getRepository(ServerEntity).find({ where: { isPrivate: 0 } });
  const counts = await loadMembershipCounts(dataSource, rows.map((row) => row.id));
  const ranked = rankTrendingServers(rows, counts, limit);
  const relationsByServerId = await loadServerRelationsMap(dataSource, ranked.map((row) => row.id));

  return ranked.map((row) => rowToServer(row, relationsByServerId.get(row.id)));
}
