import { DataSource } from 'typeorm';
import { ServerEntity } from '../../../entities';
import { GetServerByIdQuery } from '../../types';
import { rowToServer } from '../../mappers';
import { loadServerRelationsMap } from '../../relations';

export async function handleGetServerById(query: GetServerByIdQuery, dataSource: DataSource) {
  const repo = dataSource.getRepository(ServerEntity);
  const row = await repo.findOne({ where: { id: query.payload.serverId } });

  if (!row) {
    return null;
  }

  const relationsByServerId = await loadServerRelationsMap(dataSource, [row.id]);

  return rowToServer(row, relationsByServerId.get(row.id));
}
