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

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

// Seed minimal data if not present
$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)
    SELECT 'SKU-C190-HP','Produto HP','0000000000000','UN','00000000' WHERE NOT EXISTS (SELECT 1 FROM products WHERE codigo='SKU-C190-HP')");
$pdo->exec("INSERT INTO clients (nome, cnpj)
    SELECT 'Cliente HP','22.333.444/0001-55' WHERE NOT EXISTS (SELECT 1 FROM clients WHERE nome='Cliente HP')");
$pdo->exec("INSERT INTO suppliers (nome, cnpj)
    SELECT 'Fornecedor HP','66.777.888/0001-99' WHERE NOT EXISTS (SELECT 1 FROM suppliers WHERE nome='Fornecedor HP')");

// Create a sales order and a purchase invoice for the current period
$pdo->exec("INSERT INTO sales_orders (numero, cliente_id, valor_total, status, created_at)
    VALUES ('SO-C190-HP', (SELECT id FROM clients ORDER BY id DESC LIMIT 1), 150.00, 'aberto', NOW())");
$orderId = (int)$pdo->query("SELECT id FROM sales_orders WHERE numero='SO-C190-HP'")->fetch()['id'];
$productId = (int)$pdo->query("SELECT id FROM products WHERE codigo='SKU-C190-HP'")->fetch()['id'];
$pdo->exec("INSERT INTO sales_order_items (order_id, product_id, quantidade, preco, total) VALUES ($orderId, $productId, 3.000, 50.00, 150.00)");

$pdo->exec("INSERT INTO purchase_invoices (numero, fornecedor_id, valor, data_emissao) VALUES ('PI-C190-HP', (SELECT id FROM suppliers ORDER BY id DESC LIMIT 1), 100.00, DATE(NOW()))");
$invoiceId = (int)$pdo->query("SELECT id FROM purchase_invoices WHERE numero='PI-C190-HP'")->fetch()['id'];
$pdo->exec("INSERT INTO purchase_invoice_items (invoice_id, product_id, quantidade, preco, total) VALUES ($invoiceId, $productId, 2.000, 50.00, 100.00)");

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

// Basic presence
assertTrue(in_array('|C001|0|', $lines, true), 'Contains C001 open record');
// Ensure C190 exists
$hasC190 = false; foreach ($lines as $l) { if (str_starts_with($l, '|C190|')) { $hasC190 = true; break; } }
assertTrue($hasC190, 'Contains C190 consolidation record');

// Run validator: expect no issues for happy path
$issues = SpedValidator::validateSpedLines($lines);
assertTrue(empty($issues), 'SpedValidator reported issues in happy path: '.implode('; ', $issues));

echo "OK: C190 happy path without inconsistencies\n";