<?php
namespace Banyo\BrandUrlCustomizer\Controller;

use Magento\Framework\App\ActionFactory;
use Magento\Framework\App\ActionInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\App\RouterInterface;
use Magento\Framework\UrlInterface;

/**
 * Router for brand URL customization
 */
class Router implements RouterInterface
{
    /**
     * @var ActionFactory
     */
    private $actionFactory;

    /**
     * @var ResponseInterface
     */
    private $response;

    /**
     * @var UrlInterface
     */
    private $url;

    /**
     * @param ActionFactory $actionFactory
     * @param ResponseInterface $response
     * @param UrlInterface $url
     */
    public function __construct(
        ActionFactory $actionFactory,
        ResponseInterface $response,
        UrlInterface $url
    ) {
        $this->actionFactory = $actionFactory;
        $this->response = $response;
        $this->url = $url;
    }

    /**
     * Match application action by request
     *
     * @param RequestInterface $request
     * @return ActionInterface|null
     */
    public function match(RequestInterface $request)
    {
        $identifier = trim($request->getPathInfo(), '/');

        // Redirect /brand to /brands.html
        if ($identifier === 'brand') {
            $targetUrl = $this->url->getUrl('', ['_direct' => 'brands.html']);
            $this->response->setRedirect($targetUrl, 301);
            return $this->actionFactory->create(\Magento\Framework\App\Action\Redirect::class);
        }

        return null;
    }
}
