/*
 * Copyright (c) 2026 盐灯水母
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

package com.remains_cave.dungeon;

import com.mojang.serialization.Codec;
import com.mojang.serialization.MapCodec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import com.remains_cave.RemainsCaveMod;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.levelgen.Heightmap;
import net.minecraft.world.level.levelgen.structure.Structure;
import net.minecraft.world.level.levelgen.structure.StructureType;
import org.jetbrains.annotations.NotNull;

import java.util.Optional;

public class DungeonStructure extends Structure {
    public static final MapCodec<DungeonStructure> CODEC = RecordCodecBuilder.mapCodec(instance ->
            instance.group(
                    Structure.settingsCodec(instance),
                    Codec.STRING.fieldOf("routine_config").forGetter(s -> s.routineConfig)
            ).apply(instance, DungeonStructure::new)
    );

    private final String routineConfig;

    public DungeonStructure(StructureSettings settings, String routineConfig) {
        super(settings);
        this.routineConfig = routineConfig;
    }

    @Override
    protected @NotNull Optional<GenerationStub> findGenerationPoint(@NotNull GenerationContext context) {
        return onTopOfChunkCenter(context, Heightmap.Types.WORLD_SURFACE_WG, (builder) -> {
            BlockPos centerPos = context.chunkPos().getWorldPosition();
            int surfaceY = context.chunkGenerator().getBaseHeight(
                    centerPos.getX(), centerPos.getZ(),
                    Heightmap.Types.WORLD_SURFACE_WG,
                    context.heightAccessor(),
                    context.randomState()
            );
            // 下降 40 格
            int offset = 46;
            int targetY = surfaceY - offset;
            // 确保不会低于世界最低高度 + 1
            targetY = Math.max(targetY, context.heightAccessor().getMinBuildHeight() + 1);
            BlockPos origin = new BlockPos(centerPos.getX(), targetY, centerPos.getZ());
            builder.addPiece(new DungeonPiece(origin, routineConfig));
        });
    }

    @Override
    public @NotNull StructureType<?> type() {
        return RemainsCaveMod.DUNGEON_STRUCTURE_TYPE.get();
    }
}