<?php
// Simple smoke test for MatchService (CLI)
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once __DIR__ . '/../administration/includes/config.php';
require_once __DIR__ . '/../api/match_service.php';

class NullGameValidator
{
    public function validateGameResult($gameData)
    {
        return ['valid' => true];
    }
}

if (!isset($pdo) || !($pdo instanceof PDO)) {
    echo json_encode(['success' => false, 'error' => 'Database connection failed']) . PHP_EOL;
    exit(1);
}

$service = new MatchService($pdo, new NullGameValidator());
$cleanupId = null;

try {
    $payloadCreate = [
        'team1_id' => 1,
        'team2_id' => 2,
        'startTime' => gmdate('Y-m-d H:i:s'),
        'status' => 'live',
        'platform' => 'PC',
        'matchType' => 'integration-test',
        'participants' => [1, 2]
    ];

    $created = $service->createMatch($payloadCreate, 0);
    $cleanupId = (int) $created['ID'];

    $payloadUpdate = [
        'status' => 'end',
        'score' => '10:8',
        'endTime' => gmdate('Y-m-d H:i:s')
    ];

    $updated = $service->updateMatch($cleanupId, $payloadUpdate, 0);

    $updates = $service->fetchUpdates(gmdate('Y-m-d H:i:s', strtotime('-1 hour')), [], 5);

    echo json_encode([
        'success' => true,
        'created' => $created,
        'updated' => $updated,
        'recent' => $updates
    ], JSON_PRETTY_PRINT) . PHP_EOL;
} catch (Throwable $e) {
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ], JSON_PRETTY_PRINT) . PHP_EOL;
} finally {
    if ($cleanupId) {
        $stmt = $pdo->prepare('DELETE FROM matches WHERE ID = :id');
        $stmt->execute([':id' => $cleanupId]);
    }
}
