<?php
namespace Gestoreasy\Core\Fiscal;

use Gestoreasy\Core\Tenant\ConnectionManager;
use Gestoreasy\Core\Fiscal2026\Calculator2026;

class VersionRouter {
    public static function previewNfce(array $items, ?string $forceVersion = null): array {
        $pdo = ConnectionManager::forTenant();
        $cfg = TaxConfig::get($pdo);
        $version = $forceVersion ?: ($cfg['model_version'] ?? '2024');
        $env = (string)($cfg['options']['environment'] ?? 'homolog');
        if ($version === '2026') {
            $calc = new Calculator2026();
            $result = $calc->previewNfce($items, ['config' => $cfg, 'environment' => $env]);
            // Normaliza para sempre incluir a versão do modelo
            $result['model_version'] = '2026';
            return $result;
        } else {
            $calc = new Calculator();
            $result = $calc->previewNfceRJ($items, ['config' => $cfg, 'environment' => $env]);
            // Normaliza para sempre incluir a versão do modelo
            $result['model_version'] = '2024';
            return $result;
        }
    }

    public static function crossValidatePreview(array $items): array {
        $pdo = ConnectionManager::forTenant();
        $cfg = TaxConfig::get($pdo);
        $env = (string)($cfg['options']['environment'] ?? 'homolog');
        $legacy = (new Calculator())->previewNfceRJ($items, ['config' => $cfg, 'environment' => $env]);
        $next = (new Calculator2026())->previewNfce($items, ['config' => $cfg, 'environment' => $env]);
        // Normalizar para incluir model_version em ambos
        $legacy['model_version'] = '2024';
        $next['model_version'] = '2026';
        return [ 'legacy' => $legacy, 'next' => $next ];
    }
}