package xyz.tront.trontmod.gametest;

import java.util.Optional;

import net.fabricmc.fabric.api.gametest.v1.GameTest;
import net.minecraft.core.component.DataComponents;
import net.minecraft.core.registries.Registries;
import net.minecraft.gametest.framework.GameTestHelper;
import net.minecraft.resources.ResourceKey;
import net.minecraft.tags.ItemTags;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.ai.attributes.Attributes;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.item.crafting.Recipe;
import net.minecraft.world.item.crafting.RecipeHolder;
import xyz.tront.trontmod.ModItems;
import xyz.tront.trontmod.TrontMod;

/**
 * Runs inside a real headless server with datapacks loaded (gradlew build, or gradlew runGametest).
 * This is where data files (recipes, tags) get exercised for real; unit tests can't load them.
 */
public class TrontModGameTest {
	private static double attackDamage(ItemStack stack) {
		return stack.get(DataComponents.ATTRIBUTE_MODIFIERS).compute(Attributes.ATTACK_DAMAGE, 1.0, EquipmentSlot.MAINHAND);
	}

	@GameTest
	public void emeraldSwordStats(GameTestHelper helper) {
		ItemStack emerald = new ItemStack(ModItems.EMERALD_SWORD);
		ItemStack diamond = new ItemStack(Items.DIAMOND_SWORD);
		helper.assertValueEqual(attackDamage(emerald), 7.0, "emerald sword attack damage");
		helper.assertValueEqual(attackDamage(emerald), attackDamage(diamond), "emerald vs diamond attack damage");
		helper.assertValueEqual(emerald.getMaxDamage(), 1200, "emerald sword durability");
		helper.succeed();
	}

	@GameTest
	public void emeraldSwordIsTaggedAsSword(GameTestHelper helper) {
		// data/minecraft/tags/item/swords.json; this is what lets vanilla sword enchants apply.
		ItemStack emerald = new ItemStack(ModItems.EMERALD_SWORD);
		helper.assertTrue(emerald.is(ItemTags.SWORDS), "emerald sword missing from #minecraft:swords");
		helper.succeed();
	}

	@GameTest
	public void emeraldSwordRecipeLoads(GameTestHelper helper) {
		// data/trontmod/recipe/emerald_sword.json parsed and registered by the server.
		ResourceKey<Recipe<?>> key = ResourceKey.create(Registries.RECIPE, TrontMod.id("emerald_sword"));
		Optional<RecipeHolder<?>> recipe = helper.getLevel().getServer().getRecipeManager().byKey(key);
		helper.assertTrue(recipe.isPresent(), "recipe trontmod:emerald_sword did not load");
		helper.succeed();
	}
}
