<?php

namespace FiloBlu\Flow\Cron;

use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\EntityManager\MetadataPool;

/**
 *
 */
class UpdateMultistockConfigurableStockStatus
{

    /**
     * @var ResourceConnection
     */
    private $resourceConnection;
    /**
     * @var MetadataPool
     */
    private $metadataPool;

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

    /**
     * @return void
     * @throws \Exception
     */
    public function execute(){
        // update configurable stock status on inventory source item table PTRGEST-1258
        $connection = $this->resourceConnection->getConnection();

        $stock_id = $this->getStockId();
        $cpsl = $connection->getTableName('catalog_product_super_link');
        $cpe = $connection->getTableName('catalog_product_entity');
        $is1 = $connection->getTableName("inventory_stock_{$stock_id}");
        $cisi = $connection->getTableName('cataloginventory_stock_item');

        $linkFiled = $this->metadataPool->getMetadata(ProductInterface::class)->getLinkField();
        $connection->query(
            "INSERT INTO $cisi(product_id, stock_id, is_in_stock)
            SELECT
                cpe.entity_id AS product_id,
                1  AS stock_id,
                MAX(isi.is_salable) AS is_in_stock
            FROM
                $cpsl a
            INNER JOIN $cpsl b ON
                a.parent_id = b.parent_id
            INNER JOIN $cpe cpe ON
                a.parent_id = cpe.$linkFiled
            INNER JOIN $is1 isi ON
                isi.sku = cpe.sku
            GROUP  BY cpe.entity_id
            ON DUPLICATE KEY UPDATE is_in_stock = VALUES(is_in_stock)"
        );
    }

    /**
     * @return int
     * @description Having this on a separate function allows plugins to connect
     */
    public function getStockId(){
        return 2;
    }
}
