<?php

declare(strict_types=1);

namespace FiloBlu\Refilo\Remote;

use Exception;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\DB\Adapter\AdapterInterface;

/**
 * Bridge for partial reindex to write triggered ids in beehive_urls_cl
 */
class UrlPageBridge implements IndexerInterface
{
    /**
     * @var ResourceConnection
     */
    private $resourceConnection;
    /**
     * @var DeletedItemFinderInterface
     */
    private $deletedItemFinder;

    /**
     * @param ResourceConnection $resourceConnection
     * @param DeletedItemFinderInterface $deletedItemFinder
     */
    public function __construct(
        ResourceConnection $resourceConnection,
        DeletedItemFinderInterface $deletedItemFinder
    )
    {
        $this->resourceConnection = $resourceConnection;
        $this->deletedItemFinder = $deletedItemFinder;
    }

    /**
     * @return void
     */
    public function executeFull()
    {
        // Not necessary when full reindexing
    }

    /**
     * @param $id
     * @return void
     * @throws Exception
     */
    public function executeRow($id)
    {
        $this->execute([$id]);
    }

    /**
     * @param $ids
     * @return void
     * @throws Exception
     */
    public function execute($ids)
    {
        if (empty($ids)) {
            return;
        }

        $this->executeList($ids);
    }

    /**
     * @throws Exception
     */
    public function executeList(array $ids)
    {
        $connection = $this->resourceConnection->getConnection();

        $urlRewriteTable = $connection->getTableName('url_rewrite');
        $beehiveUrlCL = $connection->getTableName('beehive_urls_cl');

        $select = $connection
            ->select()
            ->from(['ur' => $urlRewriteTable], ['ur' => 'url_rewrite_id'])
            ->where('ur.entity_id IN (?)', $ids)
            ->where('ur.entity_type = ?', 'cms-page');

        $query = $connection->insertFromSelect(
            $select,
            $beehiveUrlCL,
            ['entity_id'],
            AdapterInterface::INSERT_ON_DUPLICATE
        );

        $connection->query($query);
        $connection->insertArray($beehiveUrlCL, ['entity_id'], $ids);
    }

    public function getDeletedItemFinder(): DeletedItemFinderInterface
    {
        return $this->deletedItemFinder;
    }
}
