<?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;

function assertTrue($c,$m){ if(!$c){ echo "FAIL: $m\n"; exit(1);} }
function assertEq($a,$b,$m){ if($a!==$b){ echo "FAIL: $m (".var_export($a,true)." got, expected ".var_export($b,true).")\n"; exit(1);} }

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

// Seed minimal company and product if empty
$pdo->exec("INSERT INTO empresas (nome, razao_social, cnpj, ie, email, telefone, created_at) 
    SELECT 'Empresa Demo', 'Empresa Demo Ltda', '12.345.678/0001-99', '123456789', 'contato@demo.com', '(21) 3333-3333', NOW() 
    WHERE NOT EXISTS (SELECT 1 FROM empresas)");
$pdo->exec("UPDATE empresas SET estado='RJ', cep='20000-000', logradouro='Rua Demo', numero='100', bairro='Centro', cidade='Rio de Janeiro' WHERE estado IS NULL");
$pdo->exec("INSERT INTO products (codigo, descricao, ean, unidade, ncm) VALUES ('SKU1','Produto 1','1234567890123','UN','00000000')");

$gen = new SpedFiscalGenerator($pdo);
$period = new SpedPeriod((int)date('Y'), (int)date('n'));
$lines = $gen->generate($period, ['perfil' => 'A', 'ind_ativ' => 1]);

assertTrue(is_array($lines) && count($lines) > 0, 'SPED lines generated');
// Header records
assertTrue(str_starts_with($lines[0], '|0000|'), 'First record is 0000');
assertTrue(in_array('|0001|0|', $lines, true), 'Contains 0001 open record');

// Trailer 9999 and counts
$txt = $gen->toTxt($lines);
assertTrue(is_string($txt) && strlen($txt) > 0, 'TXT serialization produced content');
$last = $lines[count($lines)-1] ?? '';
assertTrue(str_starts_with($last, '|9999|'), 'Last record is 9999');

echo "OK: SpedFiscalGenerator basic generation works (blocks 0 and 9)\n";