<?php
declare(strict_types=1);

namespace FiloBlu\Flow\Model\Channel\In;

use FiloBlu\Flow\Helper\LoggerProvider;
use FiloBlu\Flow\Model\Channel\ConfigFactory;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\DB\Adapter\AdapterInterface;
use Magento\Framework\ObjectManagerInterface;

/**
 * Class Bundle
 * @package FiloBlu\FlowOBag\Model\Channel\In
 */
class Bundle extends AbstractModel
{
    /**
     * @var ResourceConnection
     */
    private $resourceConnection;

    /**
     * @var AdapterInterface
     */
    private $connection;

    /**
     * @param LoggerProvider $loggerProvider
     * @param ConfigFactory $channelConfigFactory
     * @param ObjectManagerInterface $objectManager
     * @param ResourceConnection $resourceConnection
     */
    public function __construct(
        LoggerProvider $loggerProvider,
        ConfigFactory $channelConfigFactory,
        ObjectManagerInterface $objectManager,
        ResourceConnection $resourceConnection
    )
    {
        parent::__construct($loggerProvider, $channelConfigFactory, $objectManager);
        $this->resourceConnection = $resourceConnection;
    }


    /**
     * @return bool
     */
    public function commitData()
    {

        if (!$this->getChannelConfig()->getAutomaticBundleDefaultOptionSet()) {
            return false;
        }

        $metaFileId = $this->getFile()->getId();

        $tableName = $this->getConnection()->getTableName('flow_from_bundle');

        $connection = $this->getConnection();
        $connection->update(
            $tableName,
            ['bundle_option_default' => 0],
            ['meta_file = ?' => $metaFileId]
        );

        $temporaryTable = 'temporary_meta_ids';

        // Create a temporary table to hold the results of the subquery
        $createTemporaryTableQuery = "CREATE TEMPORARY TABLE {$temporaryTable} AS (
            SELECT MIN(x.meta_id) as meta_id
            FROM {$tableName} x
            WHERE x.meta_file = :meta_file_id
            GROUP BY x.bundle_sku, x.bundle_option_name
        )";

        $connection->query($createTemporaryTableQuery, ['meta_file_id' => $metaFileId]);

        // Update the main table using the temporary table
        $updateQuery = "UPDATE {$tableName} t1
                        JOIN {$temporaryTable} t2 ON t1.meta_id = t2.meta_id
                        SET t1.bundle_option_default = 1";

        $connection->query($updateQuery);

        // Drop the temporary table
        $dropTemporaryTableQuery = "DROP TEMPORARY TABLE IF EXISTS {$temporaryTable}";
        $connection->query($dropTemporaryTableQuery);

        return parent::commitData();
    }

    /**
     * @return AdapterInterface
     */
    protected function getConnection()
    {
        if ($this->connection === null) {
            $this->connection = $this->resourceConnection->getConnection();
        }

        return $this->connection;
    }
}
