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

use Gestoreasy\Core\Kernel;
use Gestoreasy\Core\Http\Request;
use Gestoreasy\Core\Auth\Jwt;
use Gestoreasy\Core\Tenant\ConnectionManager;

function assertTrue($cond, $msg) { if (!$cond) { echo "FAIL: $msg\n"; exit(1); } }

$kernel = new Kernel();

// Token admin para tenant default
$payload = [ 'sub' => 1, 'email' => 'admin@local', 'name' => 'Admin', 'tenant' => 'default', 'roles' => ['admin'] ];
$token = Jwt::sign($payload);
$authHeaders = [ 'x-tenant-id' => 'default', 'authorization' => 'Bearer ' . $token ];

// Garantir tabela nfce_emissions
$pdo = ConnectionManager::forTenant();
$pdo->exec('CREATE TABLE IF NOT EXISTS nfce_emissions (
  id INT AUTO_INCREMENT PRIMARY KEY,
  sale_id INT NULL,
  status VARCHAR(30) NOT NULL,
  chave VARCHAR(64) NOT NULL,
  protocolo VARCHAR(64) NULL,
  xml MEDIUMTEXT NULL,
  environment VARCHAR(20) NULL,
  messages TEXT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_nfce_chave (chave),
  INDEX idx_nfce_sale (sale_id)
)');

// Inserir um registro de teste
$chave = 'TESTE' . rand(1000,9999);
$stmt = $pdo->prepare('INSERT INTO nfce_emissions (sale_id, status, chave, protocolo, environment, messages) VALUES (NULL, ?, ?, ?, ?, ?)');
$stmt->execute(['authorized', $chave, 'PROTO123', 'homolog', json_encode(['ok' => true])]);

// Listar emissões
$reqList = new Request($authHeaders, ['page' => 1, 'per_page' => 10], [], [], 'GET', '/api/fiscal/nfce/emissions');
$resList = $kernel->handle($reqList);
assertTrue($resList->status === 200, 'GET /api/fiscal/nfce/emissions deve retornar 200');
$data = $resList->body['data'] ?? [];
assertTrue(is_array($data), 'Resposta deve conter data como array');

// Filtrar por q (chave)
$reqFilter = new Request($authHeaders, ['q' => $chave], [], [], 'GET', '/api/fiscal/nfce/emissions');
$resFilter = $kernel->handle($reqFilter);
assertTrue($resFilter->status === 200, 'GET /api/fiscal/nfce/emissions com q deve retornar 200');
$d2 = $resFilter->body['data'] ?? [];
assertTrue(is_array($d2) && count($d2) >= 1, 'Filtro por chave deve retornar ao menos 1');

echo "PASS: FiscalEmissionsEndpointsTest (list, filter by q).\n";