<?php
// Teste de integração: validação de assinatura HMAC-SHA256 para PagBank

function httpJson($method, $url, $body = null, $headers = []) {
    $ctxHeaders = [];
    foreach ($headers as $k => $v) { $ctxHeaders[] = $k . ': ' . $v; }
    $opts = [ 'http' => [ 'method' => $method, 'ignore_errors' => true, 'header' => implode("\r\n", $ctxHeaders) ] ];
    if ($body !== null) { $opts['http']['content'] = json_encode($body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); }
    $ctx = stream_context_create($opts);
    $res = @file_get_contents($url, false, $ctx);
    $status = 0; global $http_response_header; if (is_array($http_response_header)) { foreach ($http_response_header as $h) { if (preg_match('/^HTTP\/[0-9\.]+\s+(\d+)/', $h, $m)) { $status = (int)$m[1]; break; } } }
    $json = null; if ($res !== false && $res !== null && $res !== '') { $json = json_decode($res, true); }
    return [ 'status' => $status, 'json' => $json, 'raw' => $res ];
}

$base = getenv('TEST_BASE_URL') ?: 'http://127.0.0.1:8001';
$tenant = getenv('TEST_TENANT') ?: 'default';

// 1) Healthcheck
$ping = httpJson('GET', $base . '/api/payments/webhooks/pagbank?tenant=' . urlencode($tenant), null, [ 'Accept' => 'application/json' ]);
if (empty($ping['json']['ok'])) { fwrite(STDERR, "ping falhou: status {$ping['status']} body={$ping['raw']}\n" ); exit(1); }

// 2) Postar evento com assinatura válida
$secret = getenv('PAGBANK_WEBHOOK_SECRET');
if (!$secret) { fwrite(STDERR, "PAGBANK_WEBHOOK_SECRET não configurado.\n" ); exit(2); }

$event = [ 'event' => 'payment', 'payment' => [ 'id' => 'pb_sig_3001', 'status' => 'paid', 'amount' => [ 'value' => 199.90 ] ] ];
$body = json_encode($event, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$sig = hash_hmac('sha256', $body, $secret);
$hdrs = [ 'Content-Type' => 'application/json', 'x-tenant-id' => $tenant, 'x-idempotency-key' => 'pb_sig_3001', 'x-signature' => $sig ];
$post = httpJson('POST', $base . '/api/payments/webhooks/pagbank', $event, $hdrs);
if (empty($post['json']['ok'])) { fwrite(STDERR, "assinatura válida falhou: status {$post['status']} body={$post['raw']}\n" ); exit(1); }

// 3) Assinatura inválida deve ser rejeitada com 401
$hdrsBad = [ 'Content-Type' => 'application/json', 'x-tenant-id' => $tenant, 'x-idempotency-key' => 'pb_sig_3002', 'x-signature' => 'deadbeef' ];
$bad = httpJson('POST', $base . '/api/payments/webhooks/pagbank', $event, $hdrsBad);
if (empty($bad['json']['error'])) { fwrite(STDERR, "assinatura inválida não foi rejeitada: status {$bad['status']} body={$bad['raw']}\n" ); exit(1); }

echo "OK PagBankWebhookSignatureTest\n";