package com.tiedup.remake.events.combat;

import com.tiedup.remake.core.TiedUpMod;
import com.tiedup.remake.entities.EntityKidnapper;
import com.tiedup.remake.prison.PrisonerManager;
import com.tiedup.remake.prison.PrisonerRecord;
import net.minecraft.ChatFormatting;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.event.entity.player.AttackEntityEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;

/**
 * Event handler for grace period management.
 *
 * Revokes grace period when a player attacks a kidnapper.
 */
@Mod.EventBusSubscriber(
    modid = TiedUpMod.MOD_ID,
    bus = Mod.EventBusSubscriber.Bus.FORGE
)
public class GraceEventHandler {

    @SubscribeEvent
    public static void onAttackEntity(AttackEntityEvent event) {
        if (event.getEntity().level().isClientSide()) {
            return;
        }

        Entity attacker = event.getEntity();
        Entity target = event.getTarget();

        // Check if a player is attacking a kidnapper
        if (
            attacker instanceof Player player &&
            target instanceof EntityKidnapper
        ) {
            ServerLevel level = (ServerLevel) player.level();
            PrisonerManager manager = PrisonerManager.get(level);
            PrisonerRecord record = manager.getRecord(player.getUUID());

            // Check if player has grace
            if (record.isProtected(level.getGameTime())) {
                // Revoke grace by clearing protection expiry
                record.setProtectionExpiry(0);

                player.displayClientMessage(
                    Component.translatable(
                        "msg.tiedup.event.grace_lost"
                    ).withStyle(ChatFormatting.RED),
                    true
                );

                TiedUpMod.LOGGER.info(
                    "[GraceEventHandler] Player {} lost grace period by attacking kidnapper {}",
                    player.getName().getString(),
                    target.getName().getString()
                );
            }
        }
    }
}
