import { Player, EquipmentSlot, GameMode } from "@minecraft/server";

const ItemDurability = {
    onMineBlock(event) {
        const { block, source } = event; // Destructure the block and source from the event.

        // Ensure the source is a player.
        if (!(source instanceof Player)) return;

        // Check if the player has an item equipped in the main hand.
        const equippable = source.getComponent("minecraft:equippable");
        if (!equippable) return;

        const mainhand = equippable.getEquipmentSlot(EquipmentSlot.Mainhand);
        if (!mainhand.hasItem()) return;

        const itemStack = mainhand.getItem(); // Get the item stack from the main hand.

        // Handle durability if the player is not in creative mode.
        if (source.getGameMode() !== GameMode.creative) {
            const durability = itemStack.getComponent("minecraft:durability");
            if (durability) {
                const enchantable = itemStack.getComponent("minecraft:enchantable");
                const unbreakingLevel = enchantable?.getEnchantment("unbreaking")?.level;
                const damageChance = durability.getDamageChance(unbreakingLevel) / 100;

                if (Math.random() <= damageChance) {
                    durability.damage++; // Increase durability damage.

                    if (durability.damage >= durability.maxDurability) {
                        mainhand.setItem(undefined); // Break the item.
                        source.playSound("random.break"); // Play the breaking sound.
                    } else {
                        mainhand.setItem(itemStack); // Update the item.
                    }
                }
            }
        }

    }
};

export default ItemDurability;
