<?php
/**
 * OptionStore-backed module settings repository.
 *
 * @package WP_PowerSuite\Core
 * @since 1.1.0
 */

namespace WP_PowerSuite\Core;

use WP_PowerSuite\Core\Contracts\ModuleSettingsRepository;

final class OptionStoreModuleSettingsRepository implements ModuleSettingsRepository {

	private string $module_id;

	private OptionStore $store;

	public function __construct( string $module_id, ?OptionStore $store = null ) {
		$this->module_id = $module_id;
		$this->store     = $store ?? OptionStore::getInstance();
	}

	public static function forModule( string $module_id ): self {
		return new self( $module_id );
	}

	public function all( array $default = [] ): array {
		$settings = $this->store->get( $this->module_id, $default );

		return is_array( $settings ) ? $settings : $default;
	}

	public function save( array $settings ): bool {
		$success = $this->store->set( $this->module_id, $settings );
		if ( $success ) {
			self::clearCache();
		}

		return $success;
	}

	public function isEnabled(): bool {
		return $this->store->isModuleEnabled( $this->module_id );
	}

	public static function isModuleEnabled( string $module_id ): bool {
		return OptionStore::getInstance()->isModuleEnabled( $module_id );
	}

	public static function clearCache(): void {
		OptionStore::getInstance()->clearCache();
	}
}
