<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Migration\Step\UrlRewrite\Model\Version191to2000;

use Migration\ResourceModel\Source;
use Migration\Step\UrlRewrite\Version191to2000;

/**
 * Class CmsPageRewrites
 */
class CmsPageRewrites
{
    /**
     * @var Source
     */
    private $source;

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

    /**
     * @var string
     */
    protected $cmsPageTableName = 'cms_page';

    /**
     * @var string
     */
    protected $cmsPageStoreTableName = 'cms_page_store';

    /**
     * Select cms page rewrites
     *
     * @return \Magento\Framework\Db\Select
     */
    public function getSelect()
    {
        /** @var \Magento\Framework\Db\Select $select */
        $select = $this->source->getAdapter()->getSelect();
        $select->distinct()->from(
            ['cp' => $this->source->addDocumentPrefix($this->cmsPageTableName)],
            [
                new \Zend_Db_Expr('"cms-page" as `entity_type`'),
                'entity_id' => 'cp.page_id',
                'request_path' => 'cp.identifier',
                'target_path' => 'CONCAT("cms/page/view/page_id/", cp.page_id)',
                'store_id' => 'IF(cps.store_id = 0, 1, cps.store_id)',
                new \Zend_Db_Expr('1 as `is_autogenerated`')
            ]
        )->joinLeft(
            ['cps' => $this->source->addDocumentPrefix($this->cmsPageStoreTableName)],
            'cps.page_id = cp.page_id',
            []
        )->where(
            'cp.is_active = 1'
        )->where(
            'cp.identifier NOT IN(?)',
            $this->getUrlRewriteRequestPathsSelect()
        )->group(['request_path', 'cps.store_id']);

        return $select;
    }

    /**
     * Get request_paths from core_url_rewrite that matches cms_page.identifier
     *
     * @return \Magento\Framework\Db\Select
     */
    protected function getUrlRewriteRequestPathsSelect()
    {
        /** @var \Magento\Framework\Db\Select $select */
        $select = $this->source->getAdapter()->getSelect();
        $select->from(
            ['cur' => $this->source->addDocumentPrefix(Version191to2000::SOURCE)],
            ['cur.request_path']
        )->joinLeft(
            ['cp' => $this->source->addDocumentPrefix($this->cmsPageTableName)],
            'cur.request_path = cp.identifier',
            []
        );
        return $select;
    }
}
