<?php
declare(strict_types=1);

namespace Autogedal\StockLog\Plugin;

use Autogedal\StockLog\Model\StockLogger;
use Autogedal\StockLog\Model\StockSourceContext;
use Magento\CatalogImportExport\Model\StockItemImporter;
use Magento\Framework\App\ResourceConnection;

/**
 * Captures stock changes that go through MagentoStockItemImporter::import()
 * (Firebear import path — uses insertOnDuplicate directly, bypasses SetDataToLegacyStockItem).
 * Reads the before-state, lets import run, then logs what changed.
 */
class StockItemImporterPlugin
{
    private ResourceConnection $resource;
    private StockLogger $stockLogger;

    public function __construct(ResourceConnection $resource, StockLogger $stockLogger)
    {
        $this->resource    = $resource;
        $this->stockLogger = $stockLogger;
    }

    public function aroundImport(StockItemImporter $subject, callable $proceed, array $stockData): void
    {
        $skus        = array_keys($stockData);
        $stockBefore = $this->readCurrentStock($skus);

        $proceed($stockData);

        $source = StockSourceContext::getInstance()->getSource();
        if ($source === 'unknown') {
            $source = 'firebear_import';
        }

        foreach ($stockData as $sku => $newData) {
            $before        = $stockBefore[(string)$sku] ?? null;
            $qtyBefore     = $before !== null ? (float)$before['qty'] : 0.0;
            $inStockBefore = $before !== null ? (int)$before['is_in_stock'] : 0;
            $qtyAfter      = (float)($newData['qty'] ?? 0);
            $inStockAfter  = (int)($newData['is_in_stock'] ?? 0);

            if ($qtyBefore === $qtyAfter && $inStockBefore === $inStockAfter) {
                continue;
            }

            $this->stockLogger->log(
                (string)$sku,
                $qtyBefore,
                $qtyAfter,
                $inStockBefore,
                $inStockAfter,
                null,
                null,
                $source
            );
        }
    }

    private function readCurrentStock(array $skus): array
    {
        if (empty($skus)) {
            return [];
        }
        $connection = $this->resource->getConnection();
        $rows = $connection->fetchAll(
            $connection->select()
                ->from(
                    ['csi' => $this->resource->getTableName('cataloginventory_stock_item')],
                    ['qty', 'is_in_stock']
                )
                ->join(
                    ['cpe' => $this->resource->getTableName('catalog_product_entity')],
                    'cpe.entity_id = csi.product_id',
                    ['sku']
                )
                ->where('cpe.sku IN (?)', $skus)
        );
        $result = [];
        foreach ($rows as $row) {
            $result[$row['sku']] = $row;
        }
        return $result;
    }
}
