package com.yourname.premiumah.storage;

import org.bukkit.inventory.ItemStack;
import org.bukkit.util.io.BukkitObjectInputStream;
import org.bukkit.util.io.BukkitObjectOutputStream;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;

final class ItemStackSerializer {
    private ItemStackSerializer() {
    }

    static String toBase64(ItemStack item) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        try (BukkitObjectOutputStream data = new BukkitObjectOutputStream(output)) {
            data.writeObject(item);
        }
        return Base64.getEncoder().encodeToString(output.toByteArray());
    }

    static ItemStack fromBase64(String encoded) throws IOException, ClassNotFoundException {
        byte[] bytes = Base64.getDecoder().decode(encoded);
        try (BukkitObjectInputStream data = new BukkitObjectInputStream(new ByteArrayInputStream(bytes))) {
            Object object = data.readObject();
            if (!(object instanceof ItemStack item)) {
                throw new IOException("Serialized object was not an ItemStack.");
            }
            return item;
        }
    }
}
