<?php

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, 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);
$input = getInput();
$action = $input['action'] ?? '';
$db = supabase($token);

switch ($action) {
    case 'queue':
        handleQueue($db, $userId, $input);
        break;
    case 'dequeue':
        handleDequeue($db, $userId, $input);
        break;
    case 'status':
        handleStatus($db, $userId, $input);
        break;
    default:
        jsonError('Invalid action');
}

function handleQueue($db, string $userId, array $input): void {
    $gameKey = $input['game_key'] ?? 'chess';
    $timeControl = $input['time_control'] ?? 'rapid_10_0';

    $profile = $db->getOne('profiles', ['id' => 'eq.' . $userId, 'select' => 'elo_rapid,elo_blitz,elo_bullet']);
    $rating = $profile['elo_rapid'] ?? $profile['elo_blitz'] ?? 1200;

    $existing = $db->get('matchmaking_queue', [
        'player_id' => 'eq.' . $userId,
        'status' => 'eq.waiting',
        'select' => 'id'
    ]);
    if (!empty($existing) && !isset($existing['error'])) {
        jsonError('Already in queue');
    }

    // Check for available opponent
    $opponents = $db->get('matchmaking_queue', [
        'game_key' => 'eq.' . $gameKey,
        'time_control' => 'eq.' . $timeControl,
        'status' => 'eq.waiting',
        'player_id' => 'neq.' . $userId,
        'select' => 'id,player_id,rating',
        'order' => 'created_at.asc',
        'limit' => 1
    ]);

    if (!empty($opponents) && !isset($opponents['error']) && isset($opponents[0])) {
        $opponent = $opponents[0];
        $matchData = [
            'game_key' => $gameKey,
            'white_player_id' => $userId,
            'black_player_id' => $opponent['player_id'],
            'status' => 'in_progress',
            'time_control' => $timeControl,
            'current_fen' => 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1',
            'moves' => '[]'
        ];

        $match = $db->insert('matches', $matchData);
        $matchId = $match[0]['id'] ?? $match['id'] ?? null;

        if ($matchId) {
            $db->update('matchmaking_queue', [
                'status' => 'matched',
                'matched_with' => $userId,
                'match_id' => $matchId
            ], ['id' => 'eq.' . $opponent['id']]);

            jsonResponse(['match_id' => $matchId, 'color' => 'w', 'opponent_id' => $opponent['player_id']]);
        }
    }

    $queueEntry = $db->insert('matchmaking_queue', [
        'player_id' => $userId,
        'game_key' => $gameKey,
        'time_control' => $timeControl,
        'rating' => $rating,
        'status' => 'waiting'
    ]);

    jsonResponse(['queued' => true, 'id' => $queueEntry[0]['id'] ?? null]);
}

function handleDequeue($db, string $userId, array $input): void {
    $db->delete('matchmaking_queue', [
        'player_id' => 'eq.' . $userId,
        'status' => 'eq.waiting'
    ]);
    jsonResponse(['success' => true]);
}

function handleStatus($db, string $userId, array $input): void {
    $entry = $db->get('matchmaking_queue', [
        'player_id' => 'eq.' . $userId,
        'status' => 'eq.matched',
        'select' => 'match_id,matched_with',
        'limit' => 1
    ]);

    if (!empty($entry) && !isset($entry['error']) && isset($entry[0]['match_id'])) {
        $db->delete('matchmaking_queue', ['player_id' => 'eq.' . $userId]);
        jsonResponse(['match_id' => $entry[0]['match_id'], 'color' => 'b']);
    }

    jsonResponse(['waiting' => true]);
}
