<?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 UrlProductBridge implements IndexerInterface
{
    /**
     * @var ResourceConnection
     */
    private $resourceConnection;

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

    /**
     * @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 = ?', 'product');

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

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