<?php

/**
 * GET /api/session — verify Bearer token is still active and return role metadata.
 */

if ($method !== 'GET') {
    json_error('METHOD_NOT_ALLOWED', 'Method not allowed', 405);
}

$token = get_bearer_token();
if (!$token) {
    json_error('UNAUTHORIZED', 'Missing Bearer token', 401);
}

$rec = token_get_record($token);
if (!$rec) {
    json_error('UNAUTHORIZED', 'Invalid or expired token', 401);
}

$role = (string)($rec['role'] ?? '');

$username = '';
if (($rec['userID'] ?? '') !== '') {
    try {
        $opened = qdb_open_read_or_fail();
        [$pdo, $tmpDb, $lockFp] = $opened;
        $stmt = $pdo->prepare('SELECT username FROM users WHERE userID = :uid');
        $stmt->execute([':uid' => $rec['userID']]);
        $row = $stmt->fetchColumn();
        $username = $row !== false ? (string)$row : '';
        qdb_discard($tmpDb, $lockFp);
    } catch (Throwable $e) {
        qdb_handler_fail($e, 'Session check', null, $tmpDb ?? null, $lockFp ?? null);
    }
}

json_success([
    'valid'              => true,
    'user'               => $username,
    'role'               => $role,
    'userID'             => $rec['userID'] ?? '',
    'mustChangePassword' => !empty($rec['temp']),
]);
