namespace SpaceGame.Api.Universe.Scenario;

public sealed class WorldBuilder(
        WorldTopologyBuilder topologyBuilder,
        ScenarioValidationService scenarioValidationService,
        ScenarioContentBuilder contentBuilder,
        WorldRuntimeAssembler runtimeAssembler)
{
    public SimulationWorld BuildFromGeneration(WorldGenerationOptions worldGenerationOptions) =>
      BuildWorld(worldGenerationOptions, null);

    public SimulationWorld BuildFromScenario(ScenarioDefinition scenarioDefinition) =>
      BuildWorld(scenarioDefinition.WorldGeneration, scenarioDefinition);

    private SimulationWorld BuildWorld(
      WorldGenerationOptions worldGenerationOptions,
      ScenarioDefinition? scenarioDefinition)
    {
        var topology = topologyBuilder.Build(worldGenerationOptions);
        var scenario = scenarioDefinition ?? scenarioValidationService.CreateEmptyScenario(worldGenerationOptions, topology.Systems);
        scenarioValidationService.Validate(scenario, topology.Systems.Select(system => system.Id).ToHashSet(StringComparer.Ordinal));

        var content = contentBuilder.Build(scenario, topology);
        return runtimeAssembler.Assemble(worldGenerationOptions, topology, content);
    }
}
