<?php
// Isolated database and real Web Push encryption, with an in-memory HTTP transport.
declare(strict_types=1);
$root=sys_get_temp_dir().'/microchess-push-'.bin2hex(random_bytes(6));
mkdir($root.'/data',0700,true);mkdir($root.'/lib');mkdir($root.'/assets/avatars',0700,true);
foreach (['bootstrap.php','Chess.php','MoveFeedback.php','Push.php','PieceColors.php'] as $file) copy(__DIR__.'/../lib/'.$file,$root.'/lib/'.$file);
symlink(realpath(__DIR__.'/../lib/push'),$root.'/lib/push');
copy(__DIR__.'/../assets/avatars/catalog.json',$root.'/assets/avatars/catalog.json');
$_SERVER+=['HTTP_HOST'=>'localhost','REMOTE_ADDR'=>'127.0.0.1','SCRIPT_NAME'=>'/microchess/api.php'];
require $root.'/lib/bootstrap.php';
use Minishlink\WebPush\WebPush;
use Minishlink\WebPush\VAPID;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Response;
$checks=0;
function check(bool $value,string $label): void {global $checks;$checks++;if (!$value) throw new RuntimeException($label);}
try {
    $keys=pushKeys();
    check($keys===json_decode(file_get_contents($root.'/data/push-keys.json'),true),'Persistent VAPID keys');
    check(strlen(base64_decode(strtr($keys['publicKey'],'-_','+/')))===65,'P-256 VAPID public key');
    $u='local:test_user_1';$v='local:test_user_2';loginUser($v,'test_user_2');
    $device=VAPID::createVapidKeys();
    $sub=['endpoint'=>'https://fcm.googleapis.com/fcm/send/test-device','keys'=>['p256dh'=>$device['publicKey'],'auth'=>rtrim(strtr(base64_encode(random_bytes(16)),'+/','-_'),'=')]];
    pushSubscribe($u,['subscription'=>$sub]);pushSubscribe($u,['subscription'=>$sub]);
    check((int)query('SELECT COUNT(*) FROM push_subscriptions')->fetchColumn()===1,'Subscriptions are idempotent');
    pushUnsubscribe($v,$sub['endpoint']);
    check((int)query('SELECT COUNT(*) FROM push_subscriptions')->fetchColumn()===1,'Other account cannot unsubscribe device');
    foreach (['http://fcm.googleapis.com/test','https://127.0.0.1/test','https://fcm.googleapis.com.evil.example/test','https://fcm.googleapis.com:443/test','https://user@fcm.googleapis.com/test'] as $bad) {
        try {pushEndpoint($bad);check(false,'Reject unsafe endpoint');} catch (DomainException) {$checks++;}
    }
    $bad=$sub;$bad['keys']['p256dh']='BA'.str_repeat('A',85);
    try {pushSubscribe($u,['subscription'=>$bad]);check(false,'Reject invalid curve point');} catch (DomainException) {$checks++;}
    $id=startGame($u,$v);query('UPDATE games SET white=? WHERE id=?',[$v,$id]);
    $GLOBALS['push_events']=[];pushGame($id);
    $events=$GLOBALS['push_events'];
    check(count($events)===1 && array_values($events)[0]['user']===$v,'Notify player whose turn starts');
    pushSubscribe($v,['subscription'=>$sub]);
    check(query('SELECT user_id FROM push_subscriptions')->fetchColumn()===$v,'Subscription follows account on same device');
    $history=[];$mock=new MockHandler([new Response(201),new Response(410)]);
    $handler=HandlerStack::create($mock);$handler->push(Middleware::history($history));
    $sender=new WebPush(['VAPID'=>['subject'=>'https://example.com','publicKey'=>$keys['publicKey'],'privateKey'=>$keys['privateKey']]],[],5,['handler'=>$handler]);
    pushDeliver($events,$sender);
    check(count($history)===1,'Sends through HTTP transport');
    $request=$history[0]['request'];
    check($request->getHeaderLine('Content-Encoding')==='aes128gcm','Encrypted notification payload');
    check(str_starts_with($request->getHeaderLine('Authorization'),'vapid '),'VAPID authenticated notification');
    check($request->getHeaderLine('Topic')==='game-'.$id,'Coalesce each game');
    check(!str_contains((string)$request->getBody(),'Your turn'),'No plaintext payload');
    query('UPDATE games SET version=version+1 WHERE id=?',[$id]);
    pushDeliver($events,$sender);check(count($history)===1,'Skip superseded event');
    $GLOBALS['push_events']=[];pushGame($id);pushDeliver($GLOBALS['push_events'],$sender);
    check((int)query('SELECT COUNT(*) FROM push_subscriptions')->fetchColumn()===0,'Remove expired subscriptions');
    $GLOBALS['push_events']=[];query("UPDATE games SET status='ended' WHERE id=?",[$id]);pushGame($id);
    check(!$GLOBALS['push_events'],'No turn notification after game ends');
    // Rendering a production login page preserves both invitation and notification targets.
    $_GET=['game'=>'42','invite'=>str_repeat('a',48)];unset($_SESSION['user']);
    $index=str_replace("require __DIR__.'/lib/bootstrap.php';",'',file_get_contents(__DIR__.'/../index.php'));
    file_put_contents($root.'/index.php',$index);
    ob_start();require $root.'/index.php';$html=ob_get_clean();
    check(str_contains($html,'game=42'),'Sign-in link preserves notification game');
    echo "Push: $checks checks passed.\n";
} finally {
    session_write_close();
    // Only remove this test's randomly named fixture; do not traverse vendor symlink.
    $files=new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root,FilesystemIterator::SKIP_DOTS),RecursiveIteratorIterator::CHILD_FIRST);
    foreach ($files as $file) {if ($file->isDir()&&!$file->isLink()) rmdir($file->getPathname());else unlink($file->getPathname());}
    rmdir($root);
}
