<?php

declare(strict_types=1);

namespace FiloBlu\Refilo\Remote;

use Magento\Framework\Exception\NoSuchEntityException;

/**
 * Class RelatedIndexer
 * @package FiloBlu\RefiloTargetRule\Remote
 */
class RelatedIndexer extends AbstractIndexer
{
    /**
     * @param array $ids
     * @return void
     * @throws NoSuchEntityException
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function executeAction(array $ids)
    {
        // Let a misconfigured indexer fail loudly: swallowing this made mview treat the run as a
        // success and consume the changelog. executeList() logs it with context and rethrows.
        $indexTemplate = $this->getGetRemoteIndexTemplate();

        $entities = $this->entityProviderFactory->create()->withIds($ids);
        $collection = $indexTemplate->render();
        $this->write($entities, $collection);
    }

    /**
     * @param $entities
     * @param $collection
     * @return void
     * @throws NoSuchEntityException|\Magento\Framework\Exception\LocalizedException
     */
    public function write($entities, $collection)
    {
        $coreConfiguration = $this->getIndexerHelper()->getCoreConfiguration();

        if (!$coreConfiguration->isMultiDomain()) {
            $this->getConnector()->create($entities, $collection);
            return;
        }

        foreach ($coreConfiguration->getProjectIds() as $projectId) {
            $connector = $this->getConnector();
            $metadata = $connector->getMetadata();
            $metadata->setData('database', $projectId);
            $connector->setMetadata($metadata);
            $connector->create($entities, $collection);
        }
    }

    /**
     * @return string
     */
    protected function getClass(): string
    {
        return __CLASS__;
    }
}
