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

export async function handleGetAllRooms(dataSource: DataSource) {
  const currentUserId = await getCurrentUserScope(dataSource);

  if (!currentUserId) {
    return [];
  }

  const repo = dataSource.getRepository(RoomEntity);
  const ownershipRows = await dataSource.getRepository(RoomOwnerEntity).find({ where: { userId: currentUserId } });
  const roomIds = ownershipRows.map((owner) => owner.roomId);

  if (roomIds.length === 0) {
    return [];
  }

  const rows = await repo
    .createQueryBuilder('room')
    .where('room.id IN (:...roomIds)', { roomIds })
    .getMany();
  const relationsByRoomId = await loadRoomRelationsMap(dataSource, rows.map((row) => row.id));

  return rows.map((row) => rowToRoom(row, relationsByRoomId.get(row.id)));
}
