import { EntityInventoryComponent, EntityItemComponent, world } from "@minecraft/server";

/**
 * @param {import("@minecraft/server").Player} player
 */
export function arcaneRune({ id, dimension, location }) {
  /** @type {import("@minecraft/server").ItemStack[]} */
  const items = [];
  for (const entity of dimension.getEntities({ location, maxDistance: 3 })) {
    const item = entity.getComponent(EntityItemComponent.componentId);
    if (item instanceof EntityItemComponent) {
      items.push(item.itemStack);
      entity.kill();
    }
  }

  const playerSpawn = world.afterEvents.playerSpawn.subscribe(({ player }) => {
    if (id !== player.id) return;
    world.afterEvents.playerSpawn.unsubscribe(playerSpawn);

    const inventory = player.getComponent(EntityInventoryComponent.componentId);
    if (inventory instanceof EntityInventoryComponent) {
      const container = inventory.container;
      for (const item of items) {
        container?.addItem(item);
      }
    }
  });
}
