<?php
/**
 * BookiFlex Core
 *
 * @package    BookiFlex
 * @subpackage Core
 * @author     BookiFlex
 * @copyright  Copyright (c) 2025 BookiFlex
 * @license    GPL-2.0-or-later
 *
 * @link       https://bookiflex.com
 */

declare(strict_types=1);

namespace BookiFlex\Core\Infrastructure\Storage\WordPress;

use BookiFlex\Core\Infrastructure\Storage\OptionRepositoryInterface;

defined( 'ABSPATH' ) || exit;

/**
 * WordPress implementation of option repository.
 *
 * Wraps WordPress options API with automatic key prefixing.
 */
final class WordPressOptionRepository implements OptionRepositoryInterface
{
    /**
     * @param string $prefix Prefix for all option keys
     */
    public function __construct(
        private readonly string $prefix
    ) {
    }

    /**
     * {@inheritDoc}
     */
    public function get(string $key, mixed $default = null): mixed
    {
        $value = get_option($this->prefixKey($key), $default);

        return $value === false ? $default : $value;
    }

    /**
     * {@inheritDoc}
     */
    public function set(string $key, mixed $value): bool
    {
        return update_option($this->prefixKey($key), $value);
    }

    /**
     * {@inheritDoc}
     */
    public function delete(string $key): bool
    {
        return delete_option($this->prefixKey($key));
    }

    /**
     * {@inheritDoc}
     */
    public function has(string $key): bool
    {
        return get_option($this->prefixKey($key)) !== false;
    }

    /**
     * Add prefix to option key.
     *
     * @param string $key Original key
     * @return string Prefixed key
     */
    private function prefixKey(string $key): string
    {
        return $this->prefix . $key;
    }
}
