<?php

declare(strict_types=1);

namespace PrettyLinks\Pro\Targeting;

/**
 * Value object for a single targeting rule.
 *
 * Supported operators:
 *   country_in      (array<string> of 2-letter codes)
 *   country_not_in  (array<string> of 2-letter codes)
 *   device_type_in  (array<string>: mobile|tablet|desktop|bot)
 *   browser_in      (array<string>)
 *   os_in           (array<string>)
 *   hour_between    (array{from:int, to:int}  0-23)
 *   weekday_in      (array<int> 0=sunday..6=saturday)
 *   date_between    (array{from:string, to:string}  strtotime-parseable)
 *   all_of          (array<array{operator:string, value:mixed}>  compound AND)
 */
class Rule
{
    /**
     * The comparison operator.
     *
     * @var string
     */
    public $operator;

    /**
     * The value compared against by the operator.
     *
     * @var mixed
     */
    public $value;

    /**
     * The destination URL applied when the rule matches.
     *
     * @var string
     */
    public $redirectTo;

    /**
     * Builds a targeting rule value object.
     *
     * @param string $operator   The comparison operator.
     * @param mixed  $value      The value compared against by the operator.
     * @param string $redirectTo The destination URL applied when the rule matches.
     */
    public function __construct(string $operator, $value, string $redirectTo)
    {
        $this->operator   = $operator;
        $this->value      = $value;
        $this->redirectTo = $redirectTo;
    }

    /**
     * Builds a rule from a stored associative array.
     *
     * @param array<string, mixed> $data The raw rule data.
     *
     * @return self
     */
    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['operator'] ?? ''),
            $data['value'] ?? null,
            (string) ($data['redirect_to'] ?? '')
        );
    }
}
