<?php

declare(strict_types=1);

namespace MonsieurBiz\SyliusSearchPlugin\Helper;

class SortHelper implements SortHelperInterface
{
    public function getSortParamByField(
        string $field,
        string $channel,
        string $order = 'asc',
        string $taxon = '',
    ): array {
        return match ($field) {
            'name', 'created_at' => $this->buildSort('attributes.value.keyword', $order, 'attributes', 'attributes.code', $field),
            'price' => $this->buildSort('price.value', $order, 'price', 'price.channel', $channel),
            'position' => $this->buildSort('taxon.productPosition', $order, 'taxon', 'taxon.code', $taxon),
            default => $this->buildSort('attributes.value.keyword', $order, 'attributes', 'attributes.code', 'dummy'),
        };
    }

    public function buildSort(
        string $field,
        string $order,
        string $nestedPath,
        string $sortFilterField,
        string $sortFilterValue,
    ): array {
        return [
            $field => [
                'order' => $order,
                'nested' => [
                    'path' => $nestedPath,
                    'filter' => [
                        'term' => [$sortFilterField => $sortFilterValue],
                    ],
                ],
            ],
        ];
    }
}
