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

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

function assertTrue($cond, $msg) { if (!$cond) { echo "FAIL: $msg\n"; exit(1); } }

$kernel = new Kernel();

// Preparar payload e tokens
$payloadDefault = [
    'sub' => 1,
    'email' => 'user@local',
    'name' => 'User',
    'tenant' => 'default',
    'roles' => ['admin']
];
$accessTokenDefault = Jwt::sign($payloadDefault);

// 1) /api/auth/me com token válido e tenant default
$headers = ['x-tenant-id' => 'default', 'authorization' => 'Bearer ' . $accessTokenDefault];
$req = new Request($headers, [], [], [], 'GET', '/api/auth/me');
$res = $kernel->handle($req);
assertTrue($res->status === 200, 'GET /api/auth/me com token válido deve retornar 200');
assertTrue(is_array($res->body), 'Resposta de /api/auth/me deve ser JSON');
$user = $res->body['user'] ?? null;
assertTrue(is_array($user), 'Campo user deve existir e ser objeto');
assertTrue(($user['tenant'] ?? null) === 'default', 'Tenant no payload deve ser default');

// 2) /api/auth/me sem Authorization -> 401
$headersNoAuth = ['x-tenant-id' => 'default'];
$reqNoAuth = new Request($headersNoAuth, [], [], [], 'GET', '/api/auth/me');
$resNoAuth = $kernel->handle($reqNoAuth);
assertTrue($resNoAuth->status === 401, 'GET /api/auth/me sem Authorization deve retornar 401');

// 3) /api/auth/me com token de outro tenant -> 403
$payloadOtherTenant = $payloadDefault; $payloadOtherTenant['tenant'] = 'other';
$tokenOtherTenant = Jwt::sign($payloadOtherTenant);
$headersMismatch = ['x-tenant-id' => 'default', 'authorization' => 'Bearer ' . $tokenOtherTenant];
$reqMismatch = new Request($headersMismatch, [], [], [], 'GET', '/api/auth/me');
$resMismatch = $kernel->handle($reqMismatch);
assertTrue($resMismatch->status === 403, 'GET /api/auth/me com tenant mismatch deve retornar 403');

// 4) /api/auth/refresh com refresh token válido -> retorna access_token
$refreshTtl = 1209600; // 14 dias
$refreshToken = Jwt::sign($payloadDefault, $refreshTtl);
$headersRefresh = ['x-tenant-id' => 'default'];
$bodyRefresh = ['refresh_token' => $refreshToken];
$reqRefresh = new Request($headersRefresh, [], $bodyRefresh, [], 'POST', '/api/auth/refresh');
$resRefresh = $kernel->handle($reqRefresh);
assertTrue($resRefresh->status === 200, 'POST /api/auth/refresh deve retornar 200');
assertTrue(is_array($resRefresh->body), 'Resposta de /api/auth/refresh deve ser JSON');
assertTrue(is_string($resRefresh->body['access_token'] ?? null), 'Campo access_token deve existir e ser string');

echo "PASS: AuthFlow (me válido, 401 sem auth, 403 mismatch, refresh OK).\n";