package com.tiedup.remake.worldgen;

import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.core.BlockPos;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.block.Rotation;
import net.minecraft.world.level.levelgen.Heightmap;
import net.minecraft.world.level.levelgen.structure.StructureType;
import net.minecraft.world.level.levelgen.structure.pieces.StructurePiecesBuilder;

/**
 * Kidnapper Fortress - Large, rare structure.
 *
 *
 * The largest kidnapper structure type.
 * Contains:
 * - Main fortress building (kidnap_fortress) with elite kidnapper boss, cells, etc.
 *
 * Very rare spawn, contains valuable loot and dangerous enemies.
 * Structure has 9 blocks underground, so Y offset is -9.
 * Only spawns on flat terrain (max 3 blocks height difference).
 */
public class KidnapperFortressStructure extends AbstractKidnapperStructure {

    public static final Codec<KidnapperFortressStructure> CODEC =
        RecordCodecBuilder.create(instance ->
            instance
                .group(settingsCodec(instance))
                .apply(instance, KidnapperFortressStructure::new)
        );

    public KidnapperFortressStructure(StructureSettings settings) {
        super(settings);
    }

    @Override
    protected int getCheckRadius() {
        return 20;
    }

    @Override
    protected int getMaxHeightDifference() {
        return 3;
    }

    @Override
    protected int getYOffset() {
        return -9;
    }

    @Override
    protected void generatePieces(
        StructurePiecesBuilder builder,
        GenerationContext context,
        BlockPos centerPos,
        Rotation rotation
    ) {
        // Calculate fortress position with custom Y offset (9 blocks underground)
        int y =
            context
                .chunkGenerator()
                .getFirstOccupiedHeight(
                    centerPos.getX(),
                    centerPos.getZ(),
                    Heightmap.Types.WORLD_SURFACE_WG,
                    context.heightAccessor(),
                    context.randomState()
                ) +
            getYOffset();

        BlockPos fortressPos = new BlockPos(
            centerPos.getX(),
            y,
            centerPos.getZ()
        );

        builder.addPiece(
            new KidnapperCampPiece(
                context.structureTemplateManager(),
                ResourceLocation.fromNamespaceAndPath(
                    "tiedup",
                    "kidnap_fortress"
                ),
                fortressPos,
                rotation
            )
        );
    }

    @Override
    public StructureType<?> type() {
        return ModStructures.KIDNAPPER_FORTRESS.get();
    }
}
