<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Sourcing\Query;

final class QuerySorter
{
    public function __construct(
        private readonly string $field = '',
        private readonly string $direction = 'asc'
    ) {}

    public static function create(string $field = '', string $direction = 'asc'): self
    {
        return new self($field, strtolower($direction) === 'desc' ? 'desc' : 'asc');
    }

    public function sort(array $rows): array
    {
        if ($this->field === '') {
            return $rows;
        }

        usort($rows, function (array $a, array $b): int {
            $left = $this->value($a, $this->field);
            $right = $this->value($b, $this->field);

            if ($left == $right) {
                return 0;
            }

            $result = $left <=> $right;
            return $this->direction === 'desc' ? -$result : $result;
        });

        return $rows;
    }

    private function value(array $row, string $field): mixed
    {
        $parts = explode('.', $field);
        $value = $row;

        foreach ($parts as $part) {
            if (!is_array($value) || !array_key_exists($part, $value)) {
                return null;
            }

            $value = $value[$part];
        }

        return $value;
    }

    public function toArray(): array
    {
        return ['field' => $this->field, 'direction' => $this->direction];
    }
}
