<?php

declare(strict_types=1);

namespace NoahVet\Reef\Factory\RequestContext;

use NoahVet\Reef\Domain\Tool\ArrayTool;
use Symfony\Component\HttpFoundation\Request;

class FilterApplier extends AbstractApplier implements FilterApplierInterface
{
    /**
     * Build an array containing the filters present in the whitelist and the http request.
     */
    public function apply(Request $request, array $whitelist): array
    {
        $filters = [];

        foreach ($whitelist['filters'] as $supportedFilter) {
            if ($request->query->has($supportedFilter)) {
                $this->manageFilter($request, $supportedFilter, $filters);
            }
        }

        return $filters;
    }

    /**
     * @param array<mixed> $filters
     */
    private function manageFilter(Request $request, string $supportedFilter, array &$filters): void
    {
        $isArray = true;
        $isScalar = true;

        try {
            $filters[$supportedFilter] = ArrayTool::removeDuplicateValues(
                $request->query->all($supportedFilter),
            );
        } catch (\Exception) {
            $isArray = false;
        }

        if (false === $isArray) {
            try {
                $filters[$supportedFilter][] = $request->query->get($supportedFilter);
            } catch (\Exception) {
                $isScalar = false;
            }
        }

        if (!$isArray && !$isScalar) {
            throw new \LogicException('The supported filter should be an array or scalar.');
        }
    }
}
