<?php
// Simple integration test for Asaas payment link generation (mock mode)

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) Seed admin (idempotente)
$seed = httpJson('POST', $base . '/api/auth/seed-admin', [ 'email' => 'admin@local', 'password' => 'admin123', 'name' => 'Admin' ], [ 'Content-Type' => 'application/json', 'x-tenant-id' => $tenant ]);
// aceitar 200/201/409
if (!in_array($seed['status'], [200,201,409], true)) { fwrite(STDERR, "seed-admin falhou: status {$seed['status']}\n" ); }

// 2) Login
$login = httpJson('POST', $base . '/api/auth/login', [ 'email' => 'admin@local', 'password' => 'admin123' ], [ 'Content-Type' => 'application/json', 'x-tenant-id' => $tenant ]);
if ($login['status'] !== 200 || empty($login['json']['access_token'])) { fwrite(STDERR, "login falhou: status {$login['status']} body={$login['raw']}\n" ); exit(1); }
$token = $login['json']['access_token'];
$authHdrs = [ 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ' . $token, 'x-tenant-id' => $tenant ];

// 3) Salvar config do Asaas (sandbox + dummy key)
$cfg = httpJson('POST', $base . '/api/addons/asaas/config', [ 'environment' => 'sandbox', 'api_key' => 'dummy_key', 'base_url' => '' ], $authHdrs);
if (!in_array($cfg['status'], [200,201], true)) { fwrite(STDERR, "saveConfig asaas falhou: status {$cfg['status']} body={$cfg['raw']}\n" ); exit(1); }

// 4) Criar cliente mínimo
$cliBody = [ 'tipo' => 'PF', 'cpf' => '529.982.247-25', 'nome_fantasia' => 'Cliente Teste Asaas', 'razao_social' => 'Cliente Teste Asaas Ltda', 'ie' => 'ISENTO', 'estado' => 'SP' ];
$cli = httpJson('POST', $base . '/api/clientes', $cliBody, $authHdrs);
if ($cli['status'] !== 201 || empty($cli['json']['data']['id'])) { fwrite(STDERR, "criar cliente falhou: status {$cli['status']} body={$cli['raw']}\n" ); exit(1); }
$clientId = (int)$cli['json']['data']['id'];

// 5) Gerar link de pagamento
$due = (new DateTime('+5 days'))->format('Y-m-d');
$plinkReq = [ 'sale_id' => 'TEST-SALE-1001', 'client_id' => $clientId, 'amount_cents' => 12345, 'due_date' => $due, 'billing_type' => 'BOLETO' ];
$gen = httpJson('POST', $base . '/api/addons/asaas/payment-links', $plinkReq, $authHdrs);
if ($gen['status'] !== 201 || empty($gen['json']['data']['id'])) { fwrite(STDERR, "generate payment-link falhou: status {$gen['status']} body={$gen['raw']}\n" ); exit(1); }
$linkId = (int)$gen['json']['data']['id'];
if (($gen['json']['data']['status'] ?? '') !== 'aguardando compensação') { fwrite(STDERR, "status inicial incorreto\n" ); exit(1); }
if (empty($gen['json']['data']['link_url'])) { fwrite(STDERR, "link_url vazio\n" ); exit(1); }

// 6) Consultar link por ID
$get = httpJson('GET', $base . '/api/addons/asaas/payment-links/' . $linkId, null, $authHdrs);
if ($get['status'] !== 200 || empty($get['json']['data']['link_url'])) { fwrite(STDERR, "get payment-link falhou: status {$get['status']} body={$get['raw']}\n" ); exit(1); }

echo "OK AsaasPaymentLinksTest\n";