<?php
// Teste de integração: validação de assinatura HMAC-SHA256 para Mercado Pago
// Requer que o servidor tenha a variável MP_WEBHOOK_SECRET configurada.

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://localhost:8003';
$tenant = getenv('TEST_TENANT') ?: 'default';

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

// 2) Postar evento com assinatura válida (usando segredo do ambiente do servidor)
$secret = getenv('MP_WEBHOOK_SECRET');
if (!$secret) { fwrite(STDERR, "MP_WEBHOOK_SECRET não configurado no ambiente de execução do servidor.\n" ); exit(2); }

$event = [ 'type' => 'payment', 'data' => [ 'id' => 'mp_sig_2001', 'status' => 'approved', 'amount' => 55.00 ] ];
$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' => 'mp_sig_2001', 'x-signature' => $sig ];
$post = httpJson('POST', $base . '/api/payments/webhooks/mercadopago', $event, $hdrs);
if ($post['status'] !== 200 || 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' => 'mp_sig_2002', 'x-signature' => 'deadbeef' ];
$bad = httpJson('POST', $base . '/api/payments/webhooks/mercadopago', $event, $hdrsBad);
if ($bad['status'] !== 401 || empty($bad['json']['error'])) { fwrite(STDERR, "assinatura inválida não foi rejeitada: status {$bad['status']} body={$bad['raw']}\n" ); exit(1); }

echo "OK PaymentsWebhookSignatureTest\n";