import { DataSource } from 'typeorm';
import {
  RoomChannelPermissionEntity,
  RoomChannelEntity,
  RoomEntity,
  RoomOwnerEntity,
  RoomMemberEntity,
  RoomRoleEntity,
  RoomUserRoleEntity,
  MessageEntity
} from '../../../entities';
import { DeleteRoomCommand } from '../../types';
import { getCurrentUserScope } from '../../current-user-scope';

export async function handleDeleteRoom(command: DeleteRoomCommand, dataSource: DataSource): Promise<void> {
  const { roomId } = command.payload;

  await dataSource.transaction(async (manager) => {
    const currentUserId = await getCurrentUserScope(manager);

    if (!currentUserId) {
      return;
    }

    await manager.getRepository(RoomOwnerEntity).delete({ roomId, userId: currentUserId });
    await manager.getRepository(MessageEntity).delete({ roomId, ownerUserId: currentUserId });

    const remainingOwners = await manager.getRepository(RoomOwnerEntity).count({ where: { roomId } });

    if (remainingOwners > 0) {
      return;
    }

    await manager.getRepository(RoomChannelPermissionEntity).delete({ roomId });
    await manager.getRepository(RoomChannelEntity).delete({ roomId });
    await manager.getRepository(RoomMemberEntity).delete({ roomId });
    await manager.getRepository(RoomRoleEntity).delete({ roomId });
    await manager.getRepository(RoomUserRoleEntity).delete({ roomId });
    await manager.getRepository(RoomEntity).delete({ id: roomId });
  });
}
