<?php

declare(strict_types=1);

namespace FiloBlu\Refilo\Remote;

use Exception;
use FiloBlu\Refilo\Remote\IndexerInterface;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\DB\Adapter\AdapterInterface;
use Magento\Framework\EntityManager\MetadataPool;

/**
 *
 */
class LinkedProductBridge implements IndexerInterface
{
    /**
     * @var ResourceConnection
     */
    private $resourceConnection;
    /**
     * @var MetadataPool
     */
    private $metadataPool;

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

    /**
     * @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)
    {
        $link = $this->metadataPool
            ->getMetadata(ProductInterface::class)
            ->getLinkField();

        $connection = $this->resourceConnection->getConnection();

        $productTable = $connection->getTableName('catalog_product_entity');
        $productLinkTable = $connection->getTableName('catalog_product_link');
        $beehiveProductCL = $connection->getTableName('beehive_product_cl');

        $select = $connection
            ->select()
            ->from(['cpl' => $productLinkTable], [])
            ->joinLeft(['cpe' => $productTable], "cpe.$link = cpl.product_id", ['entity_id'])
            ->where('cpl.linked_product_id IN (?)', $ids);

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

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