package com.tiedup.remake.events.combat;

import com.tiedup.remake.core.TiedUpMod;
import com.tiedup.remake.state.PlayerBindState;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.monster.Monster;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.event.entity.living.LivingChangeTargetEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;

/**
 * Event handler to prevent monsters from targeting tied-up players.
 *
 * When a player is bound (has bind item), monsters will ignore them.
 * This makes sense because:
 * 1. Tied-up players are helpless and can't fight back
 * 2. Camp kidnappers protect their captives from monsters
 * 3. It reduces frustration of being killed while unable to defend
 *
 * The kidnapper's HuntMonstersGoal will handle killing nearby monsters instead.
 */
@Mod.EventBusSubscriber(
    modid = TiedUpMod.MOD_ID,
    bus = Mod.EventBusSubscriber.Bus.FORGE
)
public class MonsterTargetingHandler {

    /**
     * Called when any living entity changes its target.
     * Cancel the event if a monster tries to target a tied-up player.
     */
    @SubscribeEvent
    public static void onLivingChangeTarget(LivingChangeTargetEvent event) {
        // Only care about monsters
        if (!(event.getEntity() instanceof Monster monster)) {
            return;
        }

        // Check if new target is a player
        LivingEntity newTarget = event.getNewTarget();
        if (!(newTarget instanceof Player player)) {
            return;
        }

        // Server-side only for ServerPlayer state check
        if (!(player instanceof ServerPlayer serverPlayer)) {
            return;
        }

        // Check if player is tied up
        PlayerBindState state = PlayerBindState.getInstance(serverPlayer);
        if (state != null && state.isTiedUp()) {
            // Cancel targeting - monster ignores tied-up player
            event.setCanceled(true);

            TiedUpMod.LOGGER.debug(
                "[MonsterTargetingHandler] {} ignored tied-up player {}",
                monster.getName().getString(),
                player.getName().getString()
            );
        }
    }
}
