<?php
declare(strict_types=1);

namespace Autogedal\StockLog\Model;

use Autogedal\StockLog\Model\Alert\Notifier;
use Magento\Framework\App\ResourceConnection;
use Psr\Log\LoggerInterface;

class StockLogger
{
    private ResourceConnection $resource;
    private LoggerInterface $logger;
    private Notifier $notifier;

    public function __construct(
        ResourceConnection $resource,
        LoggerInterface $logger,
        Notifier $notifier
    ) {
        $this->resource  = $resource;
        $this->logger    = $logger;
        $this->notifier  = $notifier;
    }

    public function log(
        string $sku,
        float $qtyBefore,
        float $qtyAfter,
        int $isInStockBefore,
        int $isInStockAfter,
        ?int $adminUserId = null,
        ?string $adminUsername = null,
        string $source = ''
    ): void {
        if ($source === '') {
            $source = StockSourceContext::getInstance()->getSource();
        }

        try {
            $connection = $this->resource->getConnection();
            $productId  = $this->getProductIdBySku($sku);

            $connection->insert(
                $this->resource->getTableName('autogedal_stock_log'),
                [
                    'product_id'         => $productId,
                    'sku'                => $sku,
                    'qty_before'         => $qtyBefore,
                    'qty_after'          => $qtyAfter,
                    'is_in_stock_before' => $isInStockBefore,
                    'is_in_stock_after'  => $isInStockAfter,
                    'source'             => $source,
                    'admin_user_id'      => $adminUserId,
                    'admin_username'     => $adminUsername,
                    'created_at'         => (new \DateTimeImmutable('now', new \DateTimeZone('UTC')))->format('Y-m-d H:i:s'),
                ]
            );
        } catch (\Throwable $e) {
            $this->logger->error('StockLog write failed for SKU ' . $sku . ': ' . $e->getMessage());
            return;
        }

        $this->notifier->checkAndNotify($sku, $qtyBefore, $qtyAfter, $isInStockBefore, $isInStockAfter, $source);
    }

    private function getProductIdBySku(string $sku): ?int
    {
        $connection = $this->resource->getConnection();
        $result = $connection->fetchOne(
            $connection->select()
                ->from($this->resource->getTableName('catalog_product_entity'), ['entity_id'])
                ->where('sku = ?', $sku)
        );
        return $result ? (int)$result : null;
    }
}
