package com.tiedup.remake.events.system;

import com.tiedup.remake.core.TiedUpMod;
import com.tiedup.remake.items.ItemPadlock;
import com.tiedup.remake.items.base.ILockable;
import net.minecraft.world.item.ItemStack;
import net.minecraftforge.event.AnvilUpdateEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;

/**
 * Event handler for anvil-based padlock attachment.
 *
 *
 * Allows combining a bondage item (ILockable) with a Padlock in the anvil
 * to make the item "lockable". A lockable item can then be locked with a Key.
 *
 * Flow:
 * - Place ILockable item in left slot
 * - Place Padlock in right slot
 * - Output: Same item with lockable=true
 * - Cost: 1 XP level, consumes 1 padlock
 */
@Mod.EventBusSubscriber(modid = TiedUpMod.MOD_ID)
public class AnvilEventHandler {

    @SubscribeEvent
    public static void onAnvilUpdate(AnvilUpdateEvent event) {
        ItemStack left = event.getLeft(); // Bondage item
        ItemStack right = event.getRight(); // Padlock

        // Skip if either slot is empty
        if (left.isEmpty() || right.isEmpty()) return;

        // Right slot must be a Padlock
        if (!(right.getItem() instanceof ItemPadlock)) return;

        // Left slot must be ILockable
        if (!(left.getItem() instanceof ILockable lockable)) return;

        // Check if item can have a padlock attached (tape, slime, vine, web cannot)
        if (!lockable.canAttachPadlock()) {
            return; // Item type cannot have padlock (V1)
        }
        // V2 data-driven items: check definition's can_attach_padlock field
        if (!com.tiedup.remake.v2.bondage.datadriven.DataDrivenBondageItem.canAttachPadlockTo(left)) {
            return;
        }

        // Item must not already have a padlock attached
        if (lockable.isLockable(left)) {
            return; // Already has padlock
        }

        // Create result: copy of left with lockable=true
        ItemStack result = left.copy();
        lockable.setLockable(result, true);

        // Set anvil output
        event.setOutput(result);
        event.setCost(1); // 1 XP level cost
        event.setMaterialCost(1); // Consume 1 padlock

        TiedUpMod.LOGGER.debug(
            "[AnvilEventHandler] Padlock attachment preview: {} + Padlock",
            left.getDisplayName().getString()
        );
    }
}
