<?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/auth.php';
require_once __DIR__ . '/../config/constants.php';

$input = getInput();
$action = $input['action'] ?? '';

switch ($action) {
    case 'list':
        handleList();
        break;
    case 'move':
        handleMove($input);
        break;
    default:
        jsonError('Invalid action');
}

function handleList(): void {
    $ch = curl_init(STOCKFISH_API . '/api/chess/bots');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if ($httpCode !== 200) {
        jsonError('Failed to fetch bots', 502);
    }

    $data = json_decode($response, true);
    jsonResponse($data);
}

function handleMove(array $input): void {
    $fen = $input['fen'] ?? '';
    $botId = $input['bot_id'] ?? '';

    if (!$fen || !$botId) {
        jsonError('fen and bot_id are required');
    }

    $payload = json_encode(['fen' => $fen, 'bot_id' => $botId]);

    $ch = curl_init(STOCKFISH_API . '/api/chess/move');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if ($httpCode !== 200) {
        $err = json_decode($response, true);
        jsonError($err['error'] ?? 'Stockfish error', $httpCode);
    }

    jsonResponse(json_decode($response, true));
}
