<?php
namespace Gestoreasy\Core\Http;

use Gestoreasy\Core\Tenant\ConnectionManager;

class StockPolicyMiddleware
{
    /**
     * Injeta no Request a política de estoque atual do tenant.
     * Chave: 'stock.allow_negative' (bool)
     */
    public static function inject(): callable
    {
        return function (Request $req) {
            $allowNeg = false;
            try {
                $pdo = ConnectionManager::forTenant();
                $row = $pdo->query('SELECT permitir_estoque_negativo FROM inventory_settings LIMIT 1')->fetch();
                $allowNeg = ((int)($row['permitir_estoque_negativo'] ?? 0)) === 1;
            } catch (\Throwable $e) {
                $allowNeg = false;
            }
            $req->set('stock.allow_negative', $allowNeg);
            return null; // seguir para próxima etapa
        };
    }
}