import { DataSource } from 'typeorm';
import { RoomEntity } from '../../../entities';
import { GetRoomQuery } from '../../types';
import { rowToRoom } from '../../mappers';
import { loadRoomRelationsMap } from '../../relations';
import { getCurrentUserScope, userOwnsRoom } from '../../current-user-scope';

export async function handleGetRoom(query: GetRoomQuery, dataSource: DataSource) {
  const currentUserId = await getCurrentUserScope(dataSource);

  if (!await userOwnsRoom(dataSource, query.payload.roomId, currentUserId)) {
    return null;
  }

  const repo = dataSource.getRepository(RoomEntity);
  const row = await repo.findOne({ where: { id: query.payload.roomId } });

  if (!row) {
    return null;
  }

  const relationsByRoomId = await loadRoomRelationsMap(dataSource, [row.id]);

  return rowToRoom(row, relationsByRoomId.get(row.id));
}
