<?php declare(strict_types=1);

namespace Newland\Toubiz\Sync\Neos\Service;

use Neos\Flow\Annotations as Flow;
use Newland\Toubiz\Sync\Neos\Domain\Repository\KeyValueRepository;

/**
 * @Flow\Scope("singleton")
 */
class UrlIdentifierRedirectService
{
    protected const PREFIX = 'url-identifier|';

    /**
     * @var KeyValueRepository
     * @Flow\Inject()
     */
    protected $repository;

    public function addRedirect(string $from, string $to): void
    {
        $redirects = $this->getRawRedirects($from);

        if (!\in_array($to, $redirects, true)) {
            $redirects[] = $to;
        }

        $this->repository->store(static::PREFIX . $from, json_encode($redirects));
    }

    public function getRedirects(string $from): array
    {
        $redirects = $this->getRawRedirects($from);
        array_unshift($redirects, $from);
        return $redirects;
    }

    private function getRawRedirects(string $from): array
    {
        $json = $this->repository->retrieve(static::PREFIX . $from);

        if (!$json) {
            return [];
        }

        return (array) json_decode($json);
    }
}
