<?php

namespace FiloBlu\Refilo\Observer;

use FiloBlu\Refilo\Helper\Data;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class BeforeBuildCanonicalUrlSelectQuery implements ObserverInterface
{
    /**
     * @var Data
     */
    private $helper;

    /**
     * @param Data $helper
     */
    public function __construct(
        Data $helper
    )
    {
        $this->helper = $helper;
    }

    public function execute(Observer $observer)
    {
        if (!$this->helper->isCanonicalUrlObserverEnabled()) {
            return;
        }

        $select = $observer->getEvent()->getSelect();
        $storeCode = $observer->getEvent()->getStoreCode();
        $contentType = $observer->getEvent()->getContentType();
        $url = $observer->getEvent()->getUrl();

        if (!in_array($contentType, explode(',', $this->helper->getCanonicalUrlObserverContentTypes()))) {
            return;
        }

        $select->reset('from')->from(['u' => 'url_rewrite'], ['request_path' => "IF (frr.target_url = '' OR frr.target_url IS NULL, '{$url}', frr.target_url)"]);
        $select->joinLeft(
            ['frr' => 'filoblu_refilo_redirect'],
            'frr.request_url like CONCAT("%/'. $storeCode .'/", u.request_path, "%") and frr.target_url not like "%/'. $storeCode .'/"',
            []
        );
        $select->order('frr.id DESC')->order('u.url_rewrite_id DESC');
        $select->limit(1);
    }
}
