package com.tiedup.remake.v2.bondage.capability;

import com.tiedup.remake.v2.bondage.IV2BondageEquipment;
import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityManager;
import net.minecraftforge.common.capabilities.CapabilityToken;
import net.minecraftforge.common.capabilities.ICapabilitySerializable;
import net.minecraftforge.common.util.LazyOptional;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * Forge capability provider for V2 bondage equipment.
 * Handles capability token, lazy optional lifecycle, and NBT serialization.
 */
public class V2BondageEquipmentProvider
    implements ICapabilitySerializable<CompoundTag>
{

    public static final Capability<IV2BondageEquipment> V2_BONDAGE_EQUIPMENT =
        CapabilityManager.get(new CapabilityToken<>() {});

    private final V2BondageEquipment equipment;
    private final LazyOptional<IV2BondageEquipment> optional;

    public V2BondageEquipmentProvider() {
        this.equipment = new V2BondageEquipment();
        this.optional = LazyOptional.of(() -> equipment);
    }

    @Override
    public @NotNull <T> LazyOptional<T> getCapability(
        @NotNull Capability<T> cap,
        @Nullable Direction side
    ) {
        if (cap == V2_BONDAGE_EQUIPMENT) {
            return optional.cast();
        }
        return LazyOptional.empty();
    }

    @Override
    @SuppressWarnings("null")
    public @NotNull CompoundTag serializeNBT() {
        return equipment.serializeNBT();
    }

    @Override
    public void deserializeNBT(CompoundTag tag) {
        equipment.deserializeNBT(tag);
    }

    /**
     * Invalidate the LazyOptional. Call when the entity is removed
     * or during player clone to prevent memory leaks.
     */
    public void invalidate() {
        optional.invalidate();
    }
}
