<?php

declare(strict_types=1);

namespace FiloBlu\Refilo\Remote;

use Exception;
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)
    {
        try {
            $indexTemplate = $this->getGetRemoteIndexTemplate();
        } catch (Exception $exception) {
            $this->logger->error($exception->getMessage(), ['exception' => $exception]);
            return;
        }

        $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__;
    }
}
