<?php
// CLI/Utility: Probar creación de access token Key2Pay usando configuración guardada
if (!defined('BASE_PATH')) { define('BASE_PATH', __DIR__ . '/..'); }
require_once BASE_PATH . '/database/connection.php';
require_once BASE_PATH . '/api/shared/ApiLoader.php';

header('Content-Type: application/json');

try {
    $db = Database::getInstance();
    $pdo = $db->getConnection();
    $client = ApiLoader::getIntegrationClient('key2pay', $pdo);
    $res = $client ? $client->createAccessToken() : ['success'=>false,'message'=>'Cliente Key2Pay no disponible'];
    $token = null; $masked = null; $expiresIn = null; $body = $res['body'] ?? null;
    if (!empty($res['json']) && is_array($res['json'])) {
        $token = $res['json']['accessToken'] ?? $res['json']['access_token'] ?? null;
        $expiresIn = $res['json']['expiresIn'] ?? null;
        if ($token && strlen($token) > 12) { $masked = substr($token,0,6) . '...' . substr($token,-6); }
    }
    echo json_encode([
        'success' => (bool)($res['success'] ?? false),
        'status' => $res['status'] ?? $res['http_code'] ?? null,
        'token_masked' => $masked,
        'expiresIn' => $expiresIn,
        'message' => $res['message'] ?? null,
        'body' => is_string($body) ? substr($body,0,500) : null
    ]);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['success'=>false,'message'=>$e->getMessage()]);
}
