<?php

header('Content-Type: application/json');
require_once __DIR__ . '/../includes/cors.php';

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

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

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? (getInput()['action'] ?? 'random');

$db = supabaseService();

if ($action === 'random') {
    $rating = intval($_GET['rating'] ?? 1200);
    $minRating = $rating - 200;
    $maxRating = $rating + 200;

    $puzzles = $db->get('puzzles', [
        'select' => 'id,fen,moves,rating,themes',
        'rating' => "gte.{$minRating}",
        'limit' => 10,
        'order' => 'id.asc'
    ]);

    if (!is_array($puzzles) || isset($puzzles['error']) || empty($puzzles)) {
        $puzzles = $db->get('puzzles', ['select' => 'id,fen,moves,rating,themes', 'limit' => 10]);
    }

    if (is_array($puzzles) && !isset($puzzles['error']) && !empty($puzzles)) {
        $puzzle = $puzzles[array_rand($puzzles)];
        jsonResponse($puzzle);
    }

    jsonError('No puzzles available', 404);
}

if ($action === 'submit' && $method === 'POST') {
    $token = requireAuth();
    $input = getInput();
    $puzzleId = $input['puzzle_id'] ?? '';
    $solved = $input['solved'] ?? false;

    jsonResponse(['success' => true, 'rating_change' => $solved ? 8 : -5]);
}

jsonError('Invalid action');
