<?php

namespace Velis\Api\Query;

use Velis\Filter;

class SortOrderParser
{
    /**
     * @param Filter $filter
     * @param array<int,string> $allowedFields
     * @param array<string,string> $nameFieldMap
     */
    public function __construct(
        private readonly Filter $filter,
        private readonly array $allowedFields = [],
        private readonly array $nameFieldMap = []
    ) {
    }

    /**
     * @return string
     */
    public function parse(): string
    {
        $orderArray = [];
        foreach ($this->parseIntoArray() as $field => $direction) {
            $orderArray[] = $field . ' ' . $direction;
        }

        return implode(', ', $orderArray);
    }

    /**
     * @return array<string,string>
     */
    public function parseIntoArray(): array
    {
        $sortBy = (string) $this->filter->get('sort_by');

        $sortOrder = explode(',', $sortBy);
        $result = [];

        foreach ($sortOrder as $sortOrderPart) {
            $parts = explode(':', $sortOrderPart);

            $field = trim($parts[0]);
            if (empty($field)) {
                continue;
            }

            $direction = strtoupper(trim($parts[1] ?? 'ASC'));

            if (!empty($this->allowedFields) && !in_array($field, $this->allowedFields)) {
                continue;
            }

            if (isset($this->nameFieldMap[$field])) {
                $field = $this->nameFieldMap[$field];
            }

            if ($direction !== 'ASC' && $direction !== 'DESC') {
                $direction = 'ASC';
            }

            $result[$field] = $direction;
        }

        return $result;
    }
}
