<?php
require_once __DIR__ . '/../bootstrap.php';

use Gestoreasy\Core\Tenant\TenantAdmin;
use Gestoreasy\Core\Tenant\ConnectionManager;
use Gestoreasy\Core\Fiscal\Sped\SpedFiscalGenerator;
use Gestoreasy\Core\Fiscal\Sped\Period as SpedPeriod;
use Gestoreasy\Core\Fiscal\Sped\Validation\SpedValidator;

function assertTrue($c,$m){ if(!$c){ echo "FAIL: $m\n"; exit(1);} }
function assertContainsLinePrefix(array $lines, string $prefix, string $msg){ foreach ($lines as $l){ if (str_starts_with($l, $prefix)) { echo "$msg\n"; return; } } echo "FAIL: $msg\n"; exit(1); }

$tenant = $argv[1] ?? 'default';
TenantAdmin::runMigrations($tenant);
$pdo = ConnectionManager::forTenant($tenant);

// Seed minimal company, product, client
$pdo->exec("INSERT INTO empresas (nome, razao_social, cnpj, ie, email, telefone, estado, cep, logradouro, numero, bairro, cidade, created_at)
    SELECT 'Empresa Demo', 'Empresa Demo Ltda', '12.345.678/0001-99', '123456789', 'contato@demo.com', '(21)3333-3333', 'RJ', '20000000', 'Rua Demo', '100', 'Centro', 'Rio de Janeiro', NOW()
    WHERE NOT EXISTS (SELECT 1 FROM empresas)");
$pdo->exec("INSERT INTO products (codigo, descricao, ean, unidade, ncm) VALUES ('SKU-IPI','Produto IPI','7890000000001','UN','00000000')");
$pdo->exec("INSERT INTO clients (nome, cnpj) VALUES ('Cliente IPI','33.222.333/0001-99')");

// Create a sales order with one item to exercise IPI rounding tolerance
$pdo->exec("INSERT INTO sales_orders (numero, cliente_id, valor_total, status, created_at) VALUES ('SO-IPI-001', (SELECT id FROM clients ORDER BY id DESC LIMIT 1), 33.33, 'aberto', DATE(NOW()))");
$orderId = (int)$pdo->query("SELECT id FROM sales_orders WHERE numero='SO-IPI-001'")->fetch()['id'];
$productId = (int)$pdo->query("SELECT id FROM products WHERE codigo='SKU-IPI'")->fetch()['id'];
$pdo->exec("INSERT INTO sales_order_items (order_id, product_id, quantidade, preco, total) VALUES ($orderId, $productId, 1.000, 33.33, 33.33)");

$gen = new SpedFiscalGenerator($pdo);
$period = new SpedPeriod((int)date('Y'), (int)date('n'));
// Set a non-integer IPI rate to induce fractional rounding (10.1%)
$lines = $gen->generate($period, ['perfil' => 'A', 'ind_ativ' => 1, 'ipi_rate' => 0.101]);

assertTrue(in_array('|C001|0|', $lines, true), 'Bloco C aberto');
assertContainsLinePrefix($lines, '|C170|', 'Possui item C170');

// Validate using SpedValidator: expect no IPI consistency issues
$issues = SpedValidator::validateSpedLines($lines);
foreach ($issues as $i){ if (str_contains($i, 'C170 VL_IPI')){ echo "FAIL: Validador encontrou problema de IPI em C170: $i\n"; exit(1);} }

echo "OK: C170 IPI respeita tolerância de arredondamento e valida sem issues\n";