<?php

namespace FiloBlu\Refilo\Model\Exporter;

use FiloBlu\Core\Model\Configuration;
use FiloBlu\Refilo\Model\Adapter\Mongo;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\ResourceConnection;
use MongoDB\Driver\Exception\Exception;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Class Redirects
 * @package FiloBlu\Refilo\Model\Exporter
 */
class Redirects extends AbstractExporter
{
    /**
     * @var ResourceConnection
     */
    private $resourceConnection;

    /**
     * Menu constructor.
     * @param ResourceConnection $resourceConnection
     * @param ScopeConfigInterface $scopeConfig
     * @param Mongo $mongo
     * @param Configuration $coreConfiguration
     */
    public function __construct(
        ResourceConnection $resourceConnection,
        ScopeConfigInterface $scopeConfig,
        Mongo $mongo,
        Configuration $coreConfiguration
    )
    {
        parent::__construct($mongo, $coreConfiguration, $scopeConfig);
        $this->resourceConnection = $resourceConnection;
    }


    public function getCollections(): iterable
    {
        yield 'redirects';
    }

    public function execute(OutputInterface $output = null)
    {
        $projectIds = [$this->getDatabase()];

        if ($this->getCoreConfiguration()->isMultiDomain()) {
            $projectIds = $this->getCoreConfiguration()->getProjectIds();
        }

        $bulkData = [];

        $result = $this->resourceConnection->getConnection()->fetchAll('SELECT * FROM `filoblu_refilo_redirect`');

        foreach ($result as $item) {
            $bulkData[] = [
                '_id'           => (int)$item['id'],
                'host'          => $item['host'],
                'request_url'   => $item['request_url'],
                'target_url'    => $item['target_url'],
                'redirect_code' => (int)$item['redirect_code']
            ];
        }

        foreach ($projectIds as $projectId) {
            if (!empty($bulkData)) {
                try {
                    $this->getConnection()->update(
                        '_id',
                        $bulkData,
                        'redirects',
                        true,
                        $projectId
                    );
                } catch (Exception $e) {
                    echo $e->getMessage();
                }
            } else {
                try {
                    $this->getConnection()->flushCollection(
                        'redirects',
                        $projectId
                    );
                } catch (Exception $e) {
                    echo $e->getMessage();
                }
            }
        }

    }
}
