<?php

declare(strict_types=1);

/**
 * @author Amasty Team
 * @copyright Copyright (c) Amasty (https://www.amasty.com)
 * @package Improved Sorting for Magento 2
 */

namespace Amasty\Sorting\Model\ResourceModel\Inventory;

use Amasty\Sorting\Model\ResourceModel\Inventory;
use Magento\Framework\App\ResourceConnection;

class GetSimpleQty
{
    /**
     * @var ResourceConnection
     */
    private $resourceConnection;

    /**
     * @var Inventory
     */
    private $inventory;

    public function __construct(ResourceConnection $resourceConnection, Inventory $inventory)
    {
        $this->resourceConnection = $resourceConnection;
        $this->inventory = $inventory;
    }

    public function execute(string $productSku, string $websiteCode, float $globalMinQty = 0): ?float
    {
        $connection = $this->resourceConnection->getConnection();

        $qtyExpression = $connection->getGreatestSql([$connection->getCheckSql(
            'stock_item.use_config_min_qty = 1',
            sprintf('source_item.quantity - %f', $globalMinQty),
            'source_item.quantity - stock_item.min_qty'
        ), 0]);

        $select = $connection->select()->from(
            ['source_item' => $this->resourceConnection->getTableName('inventory_source_item')],
            [sprintf('SUM(%s)', $qtyExpression)]
        )->joinInner(
            ['product_entity' => $this->resourceConnection->getTableName('catalog_product_entity')],
            'product_entity.sku = source_item.sku',
            []
        )->joinInner(
            ['stock_item' => $this->resourceConnection->getTableName('cataloginventory_stock_item')],
            'stock_item.product_id = product_entity.entity_id',
            []
        )->where(
            'source_code IN (?)',
            $this->inventory->getSourceCodes($websiteCode)
        )->where(
            'source_item.sku = ?',
            $productSku
        )->where(
            'source_item.status = ?',
            1
        )->group('source_item.sku');
        $qty = $connection->fetchOne($select);

        return $qty ? (float) $qty : null;
    }
}
