<?php
// Integration test for unified payments webhook (idempotency + basic flow)

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 = 'http://localhost:8003';
$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 Mercado Pago (approved) com idempotência
$event = [ 'type' => 'payment', 'data' => [ 'id' => 'mp_evt_1001', 'status' => 'approved', 'amount' => 123.45 ] ];
$hdrs = [ 'Content-Type' => 'application/json', 'x-tenant-id' => $tenant, 'x-idempotency-key' => 'mp_evt_1001' ];
$post1 = httpJson('POST', $base . '/api/payments/webhooks/mercadopago', $event, $hdrs);
if ($post1['status'] !== 200 || empty($post1['json']['ok'])) { fwrite(STDERR, "post1 falhou: status {$post1['status']} body={$post1['raw']}\n" ); exit(1); }

// 3) Repostar o mesmo evento (deve retornar duplicate=true)
$post2 = httpJson('POST', $base . '/api/payments/webhooks/mercadopago', $event, $hdrs);
if ($post2['status'] !== 200 || empty($post2['json']['duplicate'])) { fwrite(STDERR, "idempotência falhou: status {$post2['status']} body={$post2['raw']}\n" ); exit(1); }

echo "OK PaymentsWebhookTest\n";