package thb.jeanluc.adventure.loader;

import thb.jeanluc.adventure.loader.dto.CombinationDto;
import thb.jeanluc.adventure.loader.dto.ConditionDto;
import thb.jeanluc.adventure.loader.dto.EffectDto;
import thb.jeanluc.adventure.model.Combination;
import thb.jeanluc.adventure.model.item.Item;

import java.util.List;
import java.util.Map;

/** Builds {@link Combination}s from {@link CombinationDto}s, validating item ids. */
public final class CombinationFactory {

    private CombinationFactory() {
    }

    public static Combination fromDto(CombinationDto dto, Map<String, Item> items) {
        requireItem(items, dto.a(), "a");
        requireItem(items, dto.b(), "b");
        if (dto.a().equals(dto.b())) {
            throw new WorldLoadException(
                    "Combination cannot combine an item with itself: '" + dto.a() + "'");
        }
        if (dto.consume() != null) {
            for (String id : dto.consume()) {
                requireItem(items, id, "consume");
            }
        }
        if (dto.produce() != null) {
            requireItem(items, dto.produce(), "produce");
        }
        return new Combination(
                dto.a(),
                dto.b(),
                ConditionDto.toModelList(dto.requires()),
                dto.consume() == null ? List.of() : List.copyOf(dto.consume()),
                dto.produce(),
                EffectDto.toModelList(dto.effects()),
                dto.response(),
                dto.failText());
    }

    private static void requireItem(Map<String, Item> items, String id, String field) {
        if (id == null) {
            throw new WorldLoadException("Combination '" + field + "' is missing an item id");
        }
        if (!items.containsKey(id)) {
            throw new WorldLoadException(
                    "Combination references unknown item '" + id + "' (field '" + field + "')");
        }
    }
}
