<?php
declare(strict_types=1);

namespace Autogedal\StockSourceRouter\Plugin;

use Autogedal\StockSourceRouter\Logger\Logger;
use Autogedal\StockSourceRouter\Model\FallbackState;
use Autogedal\StockSourceRouter\Model\RouterConfig;
use Magento\CatalogImportExport\Model\StockItemImporter;

class FirebearRouterPlugin
{
    private const FIREBEAR_SOURCE = 'firebear_import';

    public function __construct(
        private readonly RouterConfig $routerConfig,
        private readonly FallbackState $fallbackState,
        private readonly Logger $logger
    ) {}

    public function aroundImport(StockItemImporter $subject, callable $proceed, array $stockData): void
    {
        $filtered = [];

        foreach ($stockData as $sku => $data) {
            $sku  = (string)$sku;
            $rule = $this->routerConfig->getRuleForSku($sku);

            if ($rule === null) {
                // Not in any routing rule — allow
                $filtered[$sku] = $data;
                continue;
            }

            $primarySource  = $rule['primary_source'];
            $fallbackSource = $rule['fallback_source'];
            $isOnFallback   = $this->fallbackState->isOnFallback($sku);
            $qty            = (float)($data['qty'] ?? 0);

            $sSku = $this->sanitize($sku);

            if ($primarySource === self::FIREBEAR_SOURCE) {
                if ($qty == 0) {
                    if (!$fallbackSource) {
                        // No fallback configured — let qty=0 pass through normally
                        $filtered[$sku] = $data;
                        continue;
                    }
                    if (!$isOnFallback) {
                        $this->logger->info("[FALLBACK ACTIVATED] sku=$sSku primary=firebear qty=0 fallback=" . $this->sanitize($fallbackSource));
                        $this->fallbackState->activate($sku, $primarySource);
                        $filtered[$sku] = $data;
                    } else {
                        $this->logger->debug("[SKIP] sku=$sSku source=firebear qty=0 — fallback already active");
                    }
                    continue;
                }
                if ($qty > 0 && $isOnFallback) {
                    $this->logger->info("[FALLBACK DEACTIVATED] sku=$sSku primary=firebear qty=$qty — primary back in stock");
                    $this->fallbackState->deactivate($sku);
                }
                $filtered[$sku] = $data;
                continue;
            }

            if ($fallbackSource === self::FIREBEAR_SOURCE && $isOnFallback) {
                $this->logger->debug("[ALLOWED] sku=$sSku fallback=firebear qty=$qty");
                $filtered[$sku] = $data;
                continue;
            }

            $this->logger->debug("[BLOCKED] sku=$sSku source=firebear blocked — primary=" . $this->sanitize($primarySource) . " fallback_active=" . ($isOnFallback ? 'yes' : 'no'));
        }

        if (!empty($filtered)) {
            $proceed($filtered);
        }
    }

    private function sanitize(string $value, int $maxLen = 100): string
    {
        return substr(preg_replace('/[\r\n\t\x00-\x1f\x7f]/', '', $value), 0, $maxLen);
    }
}
