<?php

declare(strict_types=1);

namespace Core\General\Filter;

use Core\General\Database\Enum\OrderType;
use Core\General\Filter\ValueObject\SortParameter;

class BaseFilter
{
    /**
     * @param string[] $orderByMap
     */
    public function __construct(
        protected ?string $filter = null,
        protected array $orderByMap = [],
    ) {
        $this->filter = $filter === 'null' || $filter === '' ? null : $filter;
    }

    public function getFilter(): ?string
    {
        return $this->filter;
    }

    /** @return string[] */
    public function getOrderByMap(): array
    {
        return $this->orderByMap;
    }

    /**
     * @return SortParameter[]
     */
    public function buildOrderByMap(): array
    {
        $orderByMap = [];
        foreach ($this->orderByMap as $orderByField => $orderByType) {
            if (\in_array($orderByField, $this->getValidOrderByParams())
                && \in_array(strtoupper($orderByType), OrderType::getConstants())) {
                $orderByMap[] = new SortParameter($orderByField, strtoupper($orderByType));
            }
        }

        if ($orderByMap !== []) {
            return $orderByMap;
        }

        return $this->getDefaultOrderMap();
    }

    /**
     * @return string[]
     */
    public function getValidOrderByParams(): array
    {
        return [];
    }

    /**
     * @return SortParameter[]
     */
    protected function getDefaultOrderMap(): array
    {
        return [];
    }
}
