<?php

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }

require_once __DIR__ . '/../includes/supabase.php';
require_once __DIR__ . '/../includes/auth.php';

$token = requireAuth();
$userId = getUserId($token);
$db = supabase($token);

$playerId = $_GET['player_id'] ?? $userId;
$gameKey = $_GET['game_key'] ?? 'chess';
$limit = min(intval($_GET['limit'] ?? 50), 100);

$history = $db->get('rating_history', [
    'player_id' => 'eq.' . $playerId,
    'game_key' => 'eq.' . $gameKey,
    'select' => 'rating_before,rating_after,match_id,created_at',
    'order' => 'created_at.desc',
    'limit' => $limit
]);

jsonResponse(['history' => is_array($history) && !isset($history['error']) ? $history : []]);
