<?php
// Executa fluxo: criar A3, listar, backup e deletar certificado via Kernel (sem servidor HTTP)
// Uso: php scripts/fiscal_cert_flow.php

error_reporting(E_ERROR | E_PARSE);
ini_set('display_errors', '0');

$envPath = __DIR__ . '/../.env';
if (is_file($envPath)) {
    $lines = file($envPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        $line = trim($line);
        if ($line === '' || str_starts_with($line, '#')) continue;
        [$key, $value] = array_pad(explode('=', $line, 2), 2, '');
        $key = trim($key);
        $value = trim($value);
        if ($key === '') continue;
        putenv("$key=$value");
        $_ENV[$key] = $value;
    }
}

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

use Gestoreasy\Core\Kernel;
use Gestoreasy\Core\Http\Request;
use Gestoreasy\Core\Auth\Jwt;
use Gestoreasy\Core\Auth\MfaService;

$tenant = getenv('TENANT_ID') ?: 'default';
$uid = 1;

// 1) Assinar JWT e emitir mfa_token
$jwt = Jwt::sign(['sub' => $uid, 'tenant' => $tenant]);
$mfa = MfaService::issueToken($uid);

$kernel = new Kernel();
$headers = [
    'authorization' => 'Bearer ' . $jwt,
    'x-tenant-id' => $tenant,
    'x-mfa-token' => $mfa,
    'content-type' => 'application/json',
];

function printJson($label, $res) {
    $out = [
        'label' => $label,
        'status' => $res->status ?? null,
        'body' => $res->body ?? null,
    ];
    echo json_encode($out, JSON_UNESCAPED_UNICODE) . "\n";
}

// 2) Criar A3
$bodyCreate = [
    'cnpj' => '12345678000199',
    'environment' => 'homologation',
    'module_path' => 'C:/lib/softhsm2.dll',
    'token_label' => 'TestToken',
    'cert_label' => 'TestCert',
    'pin' => '1234',
];
$reqCreate = new Request($headers, [], $bodyCreate, [], 'POST', '/api/fiscal/certificates/a3');
$resCreate = $kernel->handle($reqCreate);
printJson('create', $resCreate);
$newId = (int)($resCreate->body['id'] ?? 0);

// 3) Listar
$reqList = new Request($headers, [], [], [], 'GET', '/api/fiscal/certificates');
$resList = $kernel->handle($reqList);
printJson('list', $resList);

// 4) Backup
if ($newId > 0) {
    $reqBackup = new Request($headers, [], [], [], 'POST', "/api/fiscal/certificates/$newId/backup");
    $resBackup = $kernel->handle($reqBackup);
    printJson('backup', $resBackup);
}

// 5) Delete
if ($newId > 0) {
    $reqDelete = new Request($headers, [], [], [], 'DELETE', "/api/fiscal/certificates/$newId");
    $resDelete = $kernel->handle($reqDelete);
    printJson('delete', $resDelete);
}