<?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';

$token = requireAuth();
$userId = getUserId($token);
$limit = min(intval($_GET['limit'] ?? 20), 50);
$gameKey = $_GET['game_key'] ?? null;

$sdb = supabaseService();

// Build filter — get matches where player was white OR black
$filter = "or=(white_player_id.eq.{$userId},black_player_id.eq.{$userId})";
$url = SUPABASE_REST . '/matches?'
    . $filter
    . '&status=eq.completed'
    . '&select=id,game_key,white_player_id,black_player_id,result,time_control,bot_id,rating_change_white,rating_change_black,move_count,created_at'
    . '&order=created_at.desc'
    . '&limit=' . $limit;

if ($gameKey) {
    $url .= '&game_key=eq.' . urlencode($gameKey);
}

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'apikey: ' . SUPABASE_SERVICE_KEY,
    'Authorization: Bearer ' . SUPABASE_SERVICE_KEY,
    'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

$matches = json_decode($response, true);

if ($httpCode >= 400 || !is_array($matches)) {
    jsonResponse(['matches' => []]);
}

// Enrich with opponent names
$opponentIds = [];
foreach ($matches as $m) {
    $oppId = $m['white_player_id'] === $userId ? $m['black_player_id'] : $m['white_player_id'];
    if ($oppId && !in_array($oppId, $opponentIds)) $opponentIds[] = $oppId;
}

$names = [];
if (!empty($opponentIds)) {
    $idList = implode(',', $opponentIds);
    $profiles = $sdb->get('profiles', [
        'id' => "in.({$idList})",
        'select' => 'id,username,display_name'
    ]);
    if (is_array($profiles) && !isset($profiles['error'])) {
        foreach ($profiles as $p) {
            $names[$p['id']] = $p['display_name'] ?? $p['username'] ?? 'Player';
        }
    }
}

// Add opponent names to matches
foreach ($matches as &$m) {
    $isWhite = $m['white_player_id'] === $userId;
    $oppId = $isWhite ? $m['black_player_id'] : $m['white_player_id'];
    if ($oppId && isset($names[$oppId])) {
        if ($isWhite) $m['black_name'] = $names[$oppId];
        else $m['white_name'] = $names[$oppId];
    }
}

jsonResponse(['matches' => $matches]);
