package xyz.quickbasic.tieredrepairkits.config;

import com.hypixel.hytale.codec.builder.BuilderCodec;
import com.hypixel.hytale.codec.KeyedCodec;
import com.hypixel.hytale.codec.Codec;

import java.util.ArrayList;
import java.util.List;

public class RepairTier {

    private static final Codec<List<RecipeIngredient>> INGREDIENT_LIST_CODEC = new RecipeListCodec();

    public static final BuilderCodec<RepairTier> CODEC =
            BuilderCodec.builder(RepairTier.class, RepairTier::new)
                    .append(new KeyedCodec<>("Enabled", Codec.BOOLEAN),
                            (obj, value) -> obj.enabled = value,
                            obj -> obj.enabled).add()
                    .append(new KeyedCodec<>("RepairPenalty", Codec.DOUBLE),
                            (obj, value) -> obj.repairPenalty = value,
                            obj -> obj.repairPenalty).add()
                    .append(new KeyedCodec<>("Recipe", INGREDIENT_LIST_CODEC),
                            (obj, value) -> obj.recipe = value,
                            obj -> obj.recipe).add()
                    .build();

    private boolean enabled = true;
    private double repairPenalty = 0.0;
    private List<RecipeIngredient> recipe = new ArrayList<>();

    public RepairTier() {}

    // Getters
    public boolean isEnabled() { return enabled; }
    public double getRepairPenalty() { return repairPenalty; }
    public List<RecipeIngredient> getRecipe() { return recipe; }

    // Setters
    public void setEnabled(boolean enabled) { this.enabled = enabled; }
    public void setRepairPenalty(double repairPenalty) { this.repairPenalty = repairPenalty; }
    public void setRecipe(List<RecipeIngredient> recipe) { this.recipe = recipe; }

    // Validation
    public void validate(String tierName) {
        if (repairPenalty < -1.0 || repairPenalty > 1.0) {
            repairPenalty = 0;
        }
        validateRecipe(recipe);
    }

    private void validateRecipe(List<RecipeIngredient> ingredients) {
        if (ingredients == null) return;
        int maxIngredients = 5;
        if (ingredients.size() > maxIngredients) {
            ingredients.subList(maxIngredients, ingredients.size()).clear();
        }
        for (RecipeIngredient ing : ingredients) {
            if (ing.getItemId() == null || ing.getItemId().isBlank()) {
                ing.setItemId("Unknown");
            }
            if (ing.getQuantity() <= 0) {
                ing.setQuantity(1);
            }
        }
    }
}