<?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
    {
        $decodedUrl = urldecode($url);

        $qb = $this->createQueryBuilder();

        $qb->andWhere('_.rootRedirect = :rootRedirect')
            ->setParameter('rootRedirect', $rootRedirect);

        $qb->andWhere('_.origin = :url OR _.origin = :decodedUrl')
            ->setParameter('url', $url)
            ->setParameter('decodedUrl', $decodedUrl);

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

        $qb->addOrderBy('_.createdAt', 'ASC');
        $qb->setMaxResults(1);

        return $qb->getQuery()->getOneOrNullResult();
    }


    public function findOneByOriginLike(string $url, bool $rootRedirect = false, ?Site $site = null)
    {
        $decodedUrl = urldecode($url);

        $urlParam = str_replace('%', '\%', $url);
        $decodedUrlParam = str_replace('%', '\%', $decodedUrl);

        $qb = $this->createQueryBuilder();

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

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

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

        $qb->addOrderBy('_.createdAt', 'ASC');
        $qb->setMaxResults(1);

        return $qb->getQuery()->getOneOrNullResult();
    }
}
