package com.tiedup.remake.compat.mca.network;

import com.tiedup.remake.compat.mca.MCACompat;
import com.tiedup.remake.compat.mca.capability.MCAKidnappedCapability;
import com.tiedup.remake.core.TiedUpMod;
import com.tiedup.remake.network.ModNetwork;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.LivingEntity;

/**
 * Centralized network handling for MCA compatibility.
 *
 * All MCA-related sync operations should go through this handler.
 * This replaces scattered sync calls throughout the code.
 */
public class MCANetworkHandler {

    /**
     * Sync complete bondage state for a villager to all tracking clients.
     * Call this after any bondage equipment change.
     *
     * @param villager The MCA villager entity
     * @param cap The villager's bondage capability
     */
    public static void syncBondageState(
        LivingEntity villager,
        MCAKidnappedCapability cap
    ) {
        if (villager.level().isClientSide()) return;

        PacketSyncMCABondage packet = PacketSyncMCABondage.fromEntity(
            villager,
            cap
        );
        ModNetwork.sendToAllTrackingEntity(packet, villager);

        TiedUpMod.LOGGER.debug(
            "[MCA Network] Synced bondage state for {} to all trackers",
            villager.getName().getString()
        );
    }

    /**
     * Sync bondage state to a specific player.
     * Used when player starts tracking the villager (enters render distance).
     *
     * @param villager The MCA villager entity
     * @param cap The villager's bondage capability
     * @param tracker The player to sync to
     */
    public static void syncBondageStateTo(
        LivingEntity villager,
        MCAKidnappedCapability cap,
        ServerPlayer tracker
    ) {
        PacketSyncMCABondage packet = PacketSyncMCABondage.fromEntity(
            villager,
            cap
        );
        ModNetwork.sendToPlayer(packet, tracker);

        TiedUpMod.LOGGER.debug(
            "[MCA Network] Synced bondage state for {} to tracker {}",
            villager.getName().getString(),
            tracker.getName().getString()
        );
    }

    /**
     * Sync bondage state using the villager's capability directly.
     * Convenience method that fetches capability internally.
     *
     * @param villager The MCA villager entity
     */
    public static void syncBondageState(LivingEntity villager) {
        if (villager.level().isClientSide()) return;
        if (!MCACompat.isMCAVillager(villager)) return;

        villager
            .getCapability(MCACompat.MCA_KIDNAPPED)
            .ifPresent(cap -> {
                syncBondageState(villager, cap);
            });
    }
}
