<?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 assertContainsIssue(array $issues, string $contains, string $msg){
  foreach ($issues as $i){ if (str_contains($i, $contains)) { echo "$msg\n"; return; } }
  echo "FAIL: $msg (issue não encontrado)\n"; exit(1);
}

$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 with CST 41 (isento/suspenso) mas com base/ICMS não zero
$docs = [
  [
    'ind_oper' => 1,
    'ind_emit' => 0,
    'cod_mod'  => '57',
    'cod_sit'  => '00',
    'serie'    => '1',
    'num_doc'  => 'CTE-CST-41-ISENTO-001',
    'dt_doc'   => date('Y-m-d'),
    'dt_apur'  => date('Y-m-d'),
    'vl_doc'   => 500.00,
    'itens'    => [
      [ 'cst' => '41', 'cfop' => '5353', 'aliq_icms' => 12.00, 'vl_opr' => 500.00, 'vl_bc_icms' => 500.00, 'vl_icms' => 60.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);
assertContainsIssue($issues, 'D190 CST isento/suspenso exige base/ICMS zero', 'OK: Validator acusa CST 41 isento com base/ICMS não zero');

echo "OK: D190 com CST 41 isento porém base/ICMS não zero foi corretamente sinalizado\n";