package com.livingworld.regions;

import com.livingworld.core.services.PersistenceService;

import java.util.Optional;

/**
 * Storage class for managing region persistence operations.
 *
 * <p>This class delegates loading and saving of regions to the provided
 * {@link PersistenceService} instance, with argument validation.</p>
 */
public class RegionStorage {

    private final PersistenceService persistenceService;

    /**
     * Creates a new RegionStorage instance.
     *
     * @param persistenceService the persistence service to delegate to (must not be null)
     * @throws IllegalArgumentException if persistenceService is null
     */
    public RegionStorage(PersistenceService persistenceService) {
        if (persistenceService == null) {
            throw new IllegalArgumentException("PersistenceService must not be null");
        }
        this.persistenceService = persistenceService;
    }

    /**
     * Loads a region from storage by its coordinate.
     *
     * @param coordinate the region coordinate to load (must not be null)
     * @return an Optional containing the loaded region if it exists, or empty if not found
     * @throws IllegalArgumentException if coordinate is null
     */
    public Optional<Region> load(RegionCoordinate coordinate) {
        if (coordinate == null) {
            throw new IllegalArgumentException("RegionCoordinate must not be null");
        }
        return persistenceService.loadRegion(coordinate);
    }

    /**
     * Saves a region to storage.
     *
     * @param region the region to save (must not be null)
     * @throws IllegalArgumentException if region is null
     */
    public void save(Region region) {
        if (region == null) {
            throw new IllegalArgumentException("Region must not be null");
        }
        persistenceService.saveRegion(region);
    }

    public void markDirty(Region region) {
        if (region == null) {
            throw new IllegalArgumentException("Region must not be null");
        }
        persistenceService.markRegionDirty(region);
    }

    public void saveDirtyRegions() {
        persistenceService.saveDirtyRegions();
    }

    public void flushAll() {
        persistenceService.flushAll();
    }
}
