package com.livingworld.regions;

import java.util.UUID;

/**
 * Creates new region objects with default values.
 *
 * <p>This factory ensures that every newly created region is valid,
 * immediately dirty (so it will be saved), and initialised with sensible
 * defaults before any ecology modules are connected.</p>
 */
public class RegionFactory {

    /**
     * Creates a new region with default values.
     *
     * <p>The returned region has the following properties:
     * <ul>
     *   <li>A randomly generated UUID as its identifier</li>
     *   <li>The specified coordinate from the argument</li>
     *   <li>Lifecycle state set to {@link RegionLifecycleState#ACTIVE ACTIVE}</li>
     *   <li>{@code createdAtSimulationTick} and {@code lastUpdatedSimulationTick} both equal to {@code simulationTick}</li>
     *   <li>The dirty flag set to {@code true}</li>
     *   <li>Default {@link RegionFlags} (all flags false)</li>
     *   <li>Default {@link RegionMetrics} via {@link RegionMetrics#defaults()}</li>
     *   <li>An empty {@link RegionModuleData} container</li>
     * </ul></p>
     *
     * <p>The region is validated before being returned. If validation fails,
     * an {@link IllegalStateException} is thrown.</p>
     *
     * @param coordinate             the spatial position of the new region (must not be null)
     * @param simulationTick         the current simulation tick
     * @return a valid new Region instance
     * @throws IllegalArgumentException if coordinate is null
     */
    public Region createNewRegion(RegionCoordinate coordinate, long simulationTick) {
        if (coordinate == null) {
            throw new IllegalArgumentException("coordinate must not be null");
        }

        UUID id = UUID.randomUUID();
        RegionLifecycleState lifecycleState = RegionLifecycleState.ACTIVE;
        boolean dirty = true;
        RegionFlags flags = new RegionFlags();
        RegionMetrics metrics = RegionMetrics.defaults();
        RegionModuleData moduleData = new RegionModuleData();

        Region region = new Region(
                id,
                coordinate,
                lifecycleState,
                simulationTick,
                simulationTick,
                dirty,
                flags,
                metrics,
                moduleData
        );

        // Validate before returning; throws IllegalStateException if invalid
        region.validate();

        return region;
    }
}