<?php
namespace Banyo\BlogUrlCustomizer\Controller;

use Magento\Framework\App\Action\Forward;
use Magento\Framework\App\ActionFactory;
use Magento\Framework\App\ActionInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\App\RouterInterface;
use Magento\Framework\Url;
use Mageplaza\Blog\Helper\Data;

/**
 * Class Router
 * @package Banyo\BlogUrlCustomizer\Controller
 */
class Router implements RouterInterface
{
    const URL_SUFFIX_RSS_XML = '.xml';

    /**
     * @var ActionFactory
     */
    public $actionFactory;

    /**
     * @var Data
     */
    public $helper;

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

    /**
     * @param RequestInterface $request
     *
     * @return ActionInterface|null
     */
    public function match(RequestInterface $request)
    {
        if (!$this->helper->isEnabled()) {
            return null;
        }

        $rssAction = "rss.xml";
        $identifier = trim($request->getPathInfo(), '/');
        $urlSuffix = $this->helper->getUrlSuffix();
        $isPostView = false;

        // Check if URL has a suffix
        if ($urlSuffix && strlen($urlSuffix) > 0) {
            if (substr($identifier, -strlen($urlSuffix)) === $urlSuffix) {
                $identifier = substr($identifier, 0, strlen($identifier) - strlen($urlSuffix));
                $isPostView = true;
            }
        }
        // Check for RSS
        elseif (strpos($identifier, $rssAction) !== false) {
            $identifier = $this->checkRssIdentifier($identifier);
        }

        $routePath = explode('/', (string)$identifier);
        $routeSize = count($routePath);

        // Check if the first segment matches the blog route prefix
        if (!$routeSize || ($routeSize > 3) || (array_shift($routePath) !== $this->helper->getRoute())) {
            return null;
        }

        $request->setModuleName('mpblog')
            ->setAlias(Url::REWRITE_REQUEST_PATH_ALIAS, $identifier . $urlSuffix);

        $controller = array_shift($routePath) ?: '';

        // If no controller specified, show the blog index page
        if (!$controller) {
            $request->setControllerName('post')
                ->setActionName('index')
                ->setPathInfo('/mpblog/post/index');

            return $this->actionFactory->create(Forward::class);
        }

        $action = array_shift($routePath) ?: 'index';

        // Handle direct post URLs without 'post' segment
        if ($controller !== 'post' && $controller !== 'category' && $controller !== 'tag'
            && $controller !== 'topic' && $controller !== 'author' && $controller !== 'month') {

            // Try to load the post by URL key
            $post = $this->helper->getObjectByParam($controller, 'url_key');

            if ($post && $post->getId()) {
                // If post exists, set it as a parameter and show the post view page
                $request->setParam('id', $post->getId());
                $request->setControllerName('post')
                    ->setActionName('view')
                    ->setPathInfo('/mpblog/post/view');

                return $this->actionFactory->create(Forward::class);
            }
        }

        // Handle other controllers (category, tag, topic, etc.)
        [$controller, $request, $action] = $this->switchController($controller, $request, $action);

        $request->setControllerName($controller)
            ->setActionName($action)
            ->setPathInfo('/mpblog/' . $controller . '/' . $action);

        return $this->actionFactory->create(Forward::class);
    }

    /**
     * @param $controller
     * @param $request
     * @param $action
     * @return array
     */
    public function switchController($controller, $request, $action)
    {
        switch ($controller) {
            case 'post':
                if (!in_array($action, ['index', 'rss'])) {
                    $post = $this->helper->getObjectByParam($action, 'url_key');
                    $request->setParam('id', $post->getId());
                    $action = 'view';
                }
                break;
            case 'category':
                if (!in_array($action, ['index', 'rss'])) {
                    $category = $this->helper->getObjectByParam($action, 'url_key', Data::TYPE_CATEGORY);
                    $request->setParam('id', $category->getId());
                    $action = 'view';
                }
                break;
            case 'tag':
                $tag = $this->helper->getObjectByParam($action, 'url_key', Data::TYPE_TAG);
                $request->setParam('id', $tag->getId());
                $action = 'view';
                break;
            case 'topic':
                $topic = $this->helper->getObjectByParam($action, 'url_key', Data::TYPE_TOPIC);
                $request->setParam('id', $topic->getId());
                $action = 'view';
                break;
            case 'author':
                $author = $this->helper->getObjectByParam($action, 'url_key', Data::TYPE_AUTHOR);
                $request->setParam('id', $author->getId());
                $action = 'view';
                break;
            case 'month':
                $request->setParam('month_key', $action);
                $action = 'view';
                break;
        }

        return [$controller, $request, $action];
    }

    /**
     * check if action = rss
     *
     * @param $identifier
     *
     * @return bool
     */
    public function isRss($identifier)
    {
        $routePath = explode('/', $identifier ?? '');
        $routePath = array_pop($routePath);
        $routePath = explode('.', $routePath ?? '');
        $action = array_shift($routePath);

        return $action === 'rss';
    }

    /**
     * @param $identifier
     *
     * @return bool|null|string
     */
    public function checkRssIdentifier($identifier)
    {
        $length = strlen(self::URL_SUFFIX_RSS_XML);
        if (substr($identifier, -$length) == self::URL_SUFFIX_RSS_XML && $this->isRss($identifier)) {
            $identifier = substr($identifier, 0, strlen($identifier) - $length);

            return $identifier;
        }

        return null;
    }
}
