package com.tiedup.remake.events.captivity;

import com.tiedup.remake.core.TiedUpMod;
import com.tiedup.remake.prison.PrisonerManager;
import net.minecraft.server.level.ServerLevel;
import net.minecraftforge.event.TickEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;

/**
 * Handles periodic captivity system updates.
 *
 * Responsibilities:
 * - Expire protection periods for released prisoners
 * - Periodic validation (optional, for debugging)
 */
@Mod.EventBusSubscriber(
    modid = TiedUpMod.MOD_ID,
    bus = Mod.EventBusSubscriber.Bus.FORGE
)
public class CaptivityTickHandler {

    private static final int EXPIRY_CHECK_INTERVAL = 100; // Check every 5 seconds (100 ticks)
    private static int tickCounter = 0;

    /**
     * Handle server ticks for captivity system updates.
     */
    @SubscribeEvent
    public static void onServerTick(TickEvent.ServerTickEvent event) {
        // Only run at end of tick to avoid interfering with game logic
        if (event.phase != TickEvent.Phase.END) {
            return;
        }

        tickCounter++;

        // Run expiry check every 5 seconds
        if (tickCounter >= EXPIRY_CHECK_INTERVAL) {
            tickCounter = 0;

            // Check all loaded worlds
            for (ServerLevel level : event.getServer().getAllLevels()) {
                try {
                    PrisonerManager manager = PrisonerManager.get(level);
                    long currentTime = level.getGameTime();

                    // Expire protection for players whose grace period has ended
                    manager.tickProtectionExpiry(currentTime);
                } catch (Exception e) {
                    TiedUpMod.LOGGER.error(
                        "[CaptivityTickHandler] Error processing captivity expiry in {}: {}",
                        level.dimension().location(),
                        e.getMessage(),
                        e
                    );
                }
            }
        }
    }
}
