<?php

namespace AutoAdmin\Bundle\Seo\Repository;

use AutoAdmin\Bundle\Content\Entity\Site;
use AutoAdmin\Bundle\Content\Repository\AbstractContentRepository;
use AutoAdmin\Bundle\Seo\Entity\Redirect;

class RedirectRepository extends AbstractContentRepository
{
    public function findOneByExactOrigin(string $url, bool $rootRedirect = false, ?Site $site = null): Redirect|null
    {
        $criteria = ['origin' => $url, 'rootRedirect' => $rootRedirect];

        if ($site) {
            $criteria = [...$criteria, 'site' => $site,];
        }

        return $this->findOneBy($criteria);
    }

    public function findOneByOriginLike(string $url, bool $rootRedirect = false, ?Site $site = null)
    {
        $qb = $this->createQueryBuilder();

        $qb->andWhere(
            ':url LIKE REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(_.origin, \'*\', \'%\'), \'**\', \'%\'), \'*1*\', \'%\'), \'*2*\', \'%\'), \'*3*\', \'%\'), \'*4*\', \'%\')'
        );
        $qb->setParameter('url', str_replace('%', '\%', $url));

        if (!empty($rootRedirect)) {
            $qb->andWhere('_.rootRedirect = :root_redirect');
            $qb->setParameter('root_redirect', $rootRedirect);
        }

        if (!empty($site)) {
            $qb->andWhere('_.site = :site');
            $qb->setParameter('site', $site);
        }

        return (($res = $qb->getQuery()->execute()) && !empty($res[0])) ? $res[0] : null;
    }
}
