<?php
// Issues short-lived WebSocket ticket for ping-pong 1v1.

require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/session_bootstrap.php';

require_once __DIR__ . '/internal/respond.php';
require_once __DIR__ . '/internal/env.php';
require_once __DIR__ . '/internal/ticket.php';

if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    og_respond(['success' => false, 'error' => 'Unauthorized'], 401);
}

$userId = (int) ($_SESSION['user_id'] ?? $_SESSION['id'] ?? 0);
$username = isset($_SESSION['username']) ? trim((string) $_SESSION['username']) : '';
if ($userId <= 0) {
    og_respond(['success' => false, 'error' => 'Unauthorized (missing user session)'], 401);
}

if ($username === '') {
    og_respond([
        'success' => false,
        'error' => 'Brak username w sesji. Uzupełnij nick na koncie i zaloguj się ponownie.'
    ], 403);
}

if (mb_strlen($username) > 32) {
    og_respond([
        'success' => false,
        'error' => 'Username w sesji jest nieprawidłowy.'
    ], 403);
}

$secret = og_env('PINGPONG_1V1_SHARED_SECRET');
if (!$secret) {
    $envPath = og_find_pingpong_env_path();
    og_respond([
        'success' => false,
        'error' => 'Server not configured (missing PINGPONG_1V1_SHARED_SECRET; env=' . ($envPath ?: 'not-found') . ')'
    ], 500);
}

$now = time();
$payload = [
    'userId' => $userId,
    'username' => $username,
    'iat' => $now,
    'exp' => $now + 60,
];

$ticket = og_issue_ticket($secret, $payload);
og_respond(['success' => true, 'ticket' => $ticket, 'expiresIn' => 60]);
