<?php

declare(strict_types=1);

namespace Australcode\Rewards\Infrastructure\Settings;

use Australcode\Rewards\Domain\Settings\Settings;
use Australcode\Rewards\Domain\Settings\SettingsRepository;
use Australcode\Rewards\Service\Licensing\FeatureMap;
use Australcode\Rewards\Service\Licensing\LicenseGate;

defined( 'ABSPATH' ) || exit;

/**
 * wp_options-backed settings repository with the FeatureMap overlay.
 *
 * get() routes the stored values through FeatureMap::apply_all() so Pro-only
 * settings collapse to their free values when the license isn't Pro — even if
 * someone edited wp_options directly. save() does NOT apply the overlay: the
 * admin's real config (including Pro values) is persisted, so activating the
 * license "turns on" the saved Pro settings without reconfiguring.
 *
 * autoload=no; per-request cache avoids re-hydrating within a request.
 */
final class OptionsSettingsRepository implements SettingsRepository {

	public const OPTION_NAME = 'acrwd_settings';

	private ?Settings $cached = null;

	public function __construct(
		private readonly FeatureMap $feature_map,
		private readonly LicenseGate $gate,
	) {
	}

	public function get(): Settings {
		if ( null !== $this->cached ) {
			return $this->cached;
		}

		$raw = get_option( self::OPTION_NAME, array() );
		if ( ! is_array( $raw ) ) {
			$raw = array();
		}

		$raw          = $this->feature_map->apply_all( $raw, $this->gate->is_pro_active() );
		$this->cached = Settings::from_array( $raw );
		return $this->cached;
	}

	public function save( Settings $settings ): void {
		update_option( self::OPTION_NAME, $settings->to_array(), false );
		$this->cached = $settings;
	}
}
