<?php

declare(strict_types=1);

namespace FiloBlu\Refilo\Setup;

use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;

/**
 *
 */
class Recurring implements InstallSchemaInterface {

    /**
     * @param \Magento\Framework\Setup\SchemaSetupInterface $setup
     * @param \Magento\Framework\Setup\ModuleContextInterface $context
     * @return void
     */
    public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $this->createInventoryStockViewIfNotExists($setup);
    }

    /**
     * @param \Magento\Framework\Setup\SchemaSetupInterface $setup
     * @return void
     */
    public function createInventoryStockViewIfNotExists(SchemaSetupInterface $setup)
    {
        $inventoryStock1 = $setup->getTable('inventory_stock_1');
        if($setup->tableExists($inventoryStock1)){
            return;
        }

        $setup->startSetup();
        $catalogInventoryStockStatusTable = $setup->getTable('cataloginventory_stock_status');
        $productTable = $setup->getTable('catalog_product_entity');
        $sql = "CREATE
                SQL SECURITY INVOKER
                VIEW {$inventoryStock1}
                  AS
                    SELECT
                    DISTINCT    
                      legacy_stock_status.product_id,
                      legacy_stock_status.website_id,
                      legacy_stock_status.stock_id,
                      legacy_stock_status.qty quantity,
                      legacy_stock_status.stock_status is_salable,
                      product.sku
                    FROM $catalogInventoryStockStatusTable legacy_stock_status
                      INNER JOIN $productTable product
                        ON legacy_stock_status.product_id = product.entity_id;";
        $setup->getConnection()->query($sql);
        $setup->endSetup();
    }
}