<?php

declare(strict_types=1);

namespace App\Framework\Search;

/**
 * Represents search sorting configuration
 */
final readonly class SearchSortBy
{
    /**
     * @param array<SearchSortField> $fields
     */
    public function __construct(
        public array $fields = []
    ) {
    }

    public static function relevance(): self
    {
        return new self([
            new SearchSortField('_score', SearchSortDirection::DESC),
        ]);
    }

    public static function field(string $field, SearchSortDirection $direction = SearchSortDirection::ASC): self
    {
        return new self([
            new SearchSortField($field, $direction),
        ]);
    }

    public static function multiple(SearchSortField ...$fields): self
    {
        return new self($fields);
    }

    public function addField(string $field, SearchSortDirection $direction = SearchSortDirection::ASC): self
    {
        $fields = $this->fields;
        $fields[] = new SearchSortField($field, $direction);

        return new self($fields);
    }

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

    public function toArray(): array
    {
        return array_map(fn ($field) => $field->toArray(), $this->fields);
    }
}
