<?php

declare(strict_types=1);

namespace App\Framework\Search;

/**
 * Represents a single search hit
 */
final readonly class SearchHit
{
    /**
     * @param array<string, mixed> $source
     * @param array<string, array<string>> $highlight
     * @param array<string, mixed> $metadata
     */
    public function __construct(
        public string $id,
        public string $entityType,
        public float $score,
        public array $source,
        public array $highlight = [],
        public array $metadata = []
    ) {
    }

    public function hasHighlight(): bool
    {
        return ! empty($this->highlight);
    }

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

    public function hasMetadata(): bool
    {
        return ! empty($this->metadata);
    }

    public function getMetadata(string $key): mixed
    {
        return $this->metadata[$key] ?? null;
    }

    public function withHighlight(array $highlight): self
    {
        return new self(
            $this->id,
            $this->entityType,
            $this->score,
            $this->source,
            $highlight,
            $this->metadata
        );
    }

    public function withMetadata(array $metadata): self
    {
        return new self(
            $this->id,
            $this->entityType,
            $this->score,
            $this->source,
            $this->highlight,
            $metadata
        );
    }

    public function toArray(): array
    {
        return [
            'id' => $this->id,
            'entity_type' => $this->entityType,
            'score' => $this->score,
            'source' => $this->source,
            'highlight' => $this->highlight,
            'metadata' => $this->metadata,
        ];
    }
}
