<?php
declare(strict_types=1);

require_once dirname(__DIR__) . '/_app_guard.php';
app_guard_validate();
require_once dirname(__DIR__) . '/_auth_common.php';

try {
    $db = new PDO('sqlite:' . dirname(__DIR__) . '/db.db', null, null, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);
    auth_ensure_schema($db);
    $cfg = auth_get_p2p_node_config($db);
    $updatedAt = (string)($cfg['p2p_updated_at'] ?? '');
    $version = $updatedAt !== '' ? (int)(strtotime($updatedAt . ' UTC') ?: time()) : 0;

    auth_json_out([
        'status' => 'ok',
        'ok' => true,
        'p2p_node_url' => (string)($cfg['p2p_node_url'] ?? ''),
        'p2p_node_key' => (string)($cfg['p2p_node_key'] ?? ''),
        'configured' => !empty($cfg['configured']),
        'version' => $version,
        'updated_at' => $updatedAt,
        'server_ts' => time(),
    ]);
} catch (Throwable $error) {
    auth_json_out([
        'status' => 'error',
        'ok' => false,
        'message' => 'p2p_config_unavailable',
        'server_ts' => time(),
    ]);
}
