<?php

declare(strict_types=1);

namespace App\Application\Search\ValueObjects;

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

final readonly class SearchFilters
{
    /**
     * @param array<string, array{type: string, value: mixed}> $filters
     */
    public function __construct(
        private array $filters = []
    ) {
        $this->validate();
    }

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

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

    public function getFilter(string $field): ?array
    {
        return $this->filters[$field] ?? null;
    }

    /**
     * @return array<string, array{type: string, value: mixed}>
     */
    public function toArray(): array
    {
        return $this->filters;
    }

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

    private function validate(): void
    {
        foreach ($this->filters as $field => $filterData) {
            if (! is_array($filterData) || ! isset($filterData['type'])) {
                throw FrameworkException::create(
                    ErrorCode::VAL_BUSINESS_RULE_VIOLATION,
                    "Invalid filter format for field '{$field}'"
                );
            }
        }
    }
}
