<?php
/**
 * API: Spielstaende speichern/laden
 * GET  /api/saves?key=klimawaechter-save
 * POST /api/saves {key, data, version}
 */

$method = $_SERVER['REQUEST_METHOD'];
$db = Database::get();

if ($method === 'GET') {
    $sessionId = Session::studentId();
    if (!$sessionId) Response::json(['data' => null]);

    $key = $_GET['key'] ?? '';
    if (!$key || strlen($key) > 100) Response::error('key fehlt oder zu lang');

    $row = $db->fetchOne(
        'SELECT save_data, save_version FROM game_saves WHERE session_id = ? AND save_key = ?',
        [$sessionId, $key]
    );
    Response::json(['data' => $row ? $row['save_data'] : null, 'version' => $row ? (int)$row['save_version'] : null]);
}

if ($method === 'POST') {
    $sessionId = Session::requireStudent();
    $body = json_decode(file_get_contents('php://input'), true);
    if (!$body || !isset($body['key']) || !isset($body['data'])) {
        Response::error('key und data erforderlich');
    }
    if (strlen($body['key']) > 100 || strlen($body['data']) > 500000) {
        Response::error('Payload zu gross', 413);
    }

    $db->execute(
        'INSERT INTO game_saves (session_id, save_key, save_data, save_version)
         VALUES (?, ?, ?, ?)
         ON DUPLICATE KEY UPDATE save_data = VALUES(save_data), save_version = VALUES(save_version)',
        [$sessionId, $body['key'], $body['data'], $body['version'] ?? 2]
    );
    Response::ok();
}

Response::error('Methode nicht erlaubt', 405);
