<?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 assertNotContainsIssuePrefix(array $issues, string $prefix, string $msg){
  foreach ($issues as $i){ if (str_starts_with($i, $prefix)) { echo "FAIL: $msg (encontrado: $i)\n"; exit(1);} }
  echo "$msg\n";
}

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

// Ensure company exists
$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' WHERE estado IS NULL OR estado='' ");

$gen = new SpedFiscalGenerator($pdo);
$period = new SpedPeriod((int)date('Y'), (int)date('n'));

// Provide D100/D190 payload válido (CFOP 5353, CST 00, base/ICMS consistentes)
$docs = [
  [
    'ind_oper' => 1,
    'ind_emit' => 0,
    'cod_mod'  => '57',
    'cod_sit'  => '00',
    'serie'    => '1',
    'num_doc'  => 'CTE-D190-HAPPY-001',
    'dt_doc'   => date('Y-m-d'),
    'dt_apur'  => date('Y-m-d'),
    'vl_doc'   => 300.00,
    'itens'    => [
      [ 'cst' => '00', 'cfop' => '5353', 'aliq_icms' => 12.00, 'vl_opr' => 300.00, 'vl_bc_icms' => 300.00, 'vl_icms' => 36.00 ]
    ]
  ]
];

$lines = $gen->generate($period, ['perfil' => 'A', 'ind_ativ' => 1, 'd100_docs' => $docs]);
assertTrue(in_array('|D001|0|', $lines, true), 'Bloco D com movimento');

$issues = SpedValidator::validateSpedLines($lines);
assertNotContainsIssuePrefix($issues, 'D190 ', 'OK: D190 válido sem issues no validador');

echo "OK: Happy path do D190 não gerou inconsistências\n";