<?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 e povoar alguns dados
$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 alguns registros com datas e status distintos
$baseStatuses = ['authorized','canceled','rejected'];
foreach ($baseStatuses as $i => $st) {
    $ch = 'METR' . rand(1000,9999) . $i;
    $stmt = $pdo->prepare('INSERT INTO nfce_emissions (sale_id, status, chave, protocolo, environment, messages, created_at) VALUES (NULL, ?, ?, ?, ?, ?, ?)');
    $date = date('Y-m-d H:i:s', strtotime('-' . (2-$i) . ' days'));
    $stmt->execute([$st, $ch, 'PROTO' . $i, 'homolog', json_encode(['k'=>$st]), $date]);
}

// 1) Status consolidado
$reqStatus = new Request($authHeaders, [], [], [], 'GET', '/api/fiscal/status');
$resStatus = $kernel->handle($reqStatus);
assertTrue($resStatus->status === 200, 'GET /api/fiscal/status deve retornar 200');
$dataStatus = $resStatus->body['data'] ?? [];
assertTrue(isset($dataStatus['nfce']) && is_array($dataStatus['nfce']), 'Status deve conter chave nfce');

// 2) Métricas por dia últimos 3 dias
$from = date('Y-m-d', strtotime('-3 days'));
$to = date('Y-m-d');
$reqMetrics = new Request($authHeaders, ['from' => $from, 'to' => $to], [], [], 'GET', '/api/fiscal/metrics');
$resMetrics = $kernel->handle($reqMetrics);
assertTrue($resMetrics->status === 200, 'GET /api/fiscal/metrics deve retornar 200');
$dataMetrics = $resMetrics->body['data'] ?? [];
assertTrue(isset($dataMetrics['nfce']) && is_array($dataMetrics['nfce']), 'Métricas devem conter nfce');

// 3) SPED auto: gerar e salvar arquivo
$nowY = (int)date('Y'); $nowM = (int)date('n');
$bodyAuto = [ 'year' => $nowY, 'month' => $nowM, 'perfil' => 'A', 'cod_ver' => '017' ];
$reqAuto = new Request($authHeaders, [], $bodyAuto, [], 'POST', '/api/fiscal/sped/auto');
$resAuto = $kernel->handle($reqAuto);
assertTrue($resAuto->status === 200, 'POST /api/fiscal/sped/auto deve retornar 200');
$path = $resAuto->body['path'] ?? '';
assertTrue(is_string($path) && $path !== '', 'Resposta deve conter path do arquivo gerado');
assertTrue(is_file($path), 'Arquivo SPED exportado deve existir no path retornado');

echo "PASS: FiscalStatusMetricsEndpointsTest (status, metrics, sped auto).\n";