<?php

declare(strict_types=1);

namespace KupShop\CatalogBundle\Enum;

final readonly class Ordering
{
    public function __construct(
        public ProductOrder $orderBy,
        public OrderDirection $orderDir = OrderDirection::ASC,
    ) {
    }

    public static function fromString(string $order): ?self
    {
        $orderBy = ProductOrder::tryFromString($order);
        if (!$orderBy) {
            return null;
        }

        $orderDir = str_starts_with($order, '-')
            ? OrderDirection::DESC
            : OrderDirection::ASC;

        return new self($orderBy, $orderDir);
    }

    public function __toString(): string
    {
        $orderDir = match ($this->orderDir) {
            OrderDirection::ASC => '',
            OrderDirection::DESC => '-',
        };

        $orderBy = $this->orderBy->stringValue();

        return "{$orderDir}{$orderBy}";
    }
}
