<?php

declare(strict_types=1);

namespace App\Application\Search\ValueObjects;

use App\Framework\Exception\ErrorCode;
use App\Framework\Exception\FrameworkException;

final readonly class FieldBoosts
{
    /**
     * @param array<string, float> $boosts
     */
    public function __construct(
        private array $boosts = []
    ) {
        $this->validate();
    }

    /**
     * @param array<string, float> $boosts
     */
    public static function fromArray(array $boosts): self
    {
        return new self($boosts);
    }

    public function getBoost(string $field): float
    {
        return $this->boosts[$field] ?? 1.0;
    }

    public function hasBoost(string $field): bool
    {
        return isset($this->boosts[$field]);
    }

    /**
     * @return array<string, float>
     */
    public function toArray(): array
    {
        return $this->boosts;
    }

    public function isEmpty(): bool
    {
        return empty($this->boosts);
    }

    private function validate(): void
    {
        foreach ($this->boosts as $field => $boost) {
            if (! is_numeric($boost) || $boost < 0) {
                throw FrameworkException::create(
                    ErrorCode::VAL_BUSINESS_RULE_VIOLATION,
                    "Invalid boost value for field '{$field}'. Must be a positive number"
                );
            }
        }
    }
}
