using NUnit.Framework;

// Reproduces the reported bug: table cards on an EXISTING, already-seated non-master
// client corrupt when someone else joins the instance.
public partial class SecurityTests
{
    // Sets up a fresh HoldemGame the way a brand-new client's own local copy looks: never
    // deserialized, all fields at their compiled defaults. Deliberately does NOT register
    // the GameObject with vrc.Owners, mirroring a client that hasn't yet learned who owns
    // the table object (VrcRuntimeFake then falls back to "local player owns it").
    private HoldemGame FreshSpectatorTable(int seats)
    {
        var go = Spawn("NewJoinerTable");
        var game = go.AddComponent<HoldemGame>();
        game.seats = seats;
        game.players = new HoldemPlayer[seats];
        for (int i = 0; i < seats; i++)
        {
            var seatGo = Spawn("NewJoinerSeat_" + i, go);
            game.players[i] = seatGo.AddComponent<HoldemPlayer>();
            game.players[i].game = game;
            game.players[i].seatIdx = i;
        }
        return game;
    }

    // If a brand-new client's own Networking.IsOwner(gameObject) misreports true before
    // it has learned the table's real owner, OnDeserialization's owner gate skips
    // DeserializeState() and this client's first real update goes missing. That's a
    // separate, unconfirmed risk from the seated-player corruption below, and fixing it
    // for real means changing what OnDeserialization trusts about ownership -- not
    // attempted here. This just locks in that the fallback is now safe: a dropped sync
    // leaves the board hidden (-1), never a live-looking card.
    [Test]
    public void SpectatorMisreadAsOwnerStaysHiddenInsteadOfShowingALiveCard()
    {
        // Master deals a real hand; river is out with real cards.
        StartAs(MasterId);
        var master = TableOwnedBy(Master);
        Sit(master, 0, Victim, 1000);
        Sit(master, 1, Attacker, 1000);
        master.tableState = HoldemGame.TABLE_PLAYING;
        master.bettingRound = HoldemGame.RIVER;
        master.headsUp = true; // both hands visible without a showdown
        master.playerState[0] = HoldemGame.PLAYER_COMMITED;
        master.playerState[1] = HoldemGame.PLAYER_COMMITED;
        for (int i = 2; i < master.seats; i++) master.playerState[i] = HoldemGame.PLAYER_DEAD;
        SetField(master, "flop0", 10);
        SetField(master, "flop1", 20);
        SetField(master, "flop2", 30);
        SetField(master, "turn", 40);
        SetField(master, "river", 50);
        VrcRuntimeFake.InvokeNoArg(master, "SerializeState");

        // A brand-new spectator's own local copy of the table, seeing the very first
        // OnDeserialization of that state right as they join the instance, while their
        // own IsOwner(gameObject) read still misreports true (unmapped in vrc.Owners).
        var newJoiner = FreshSpectatorTable(master.seats);
        SetField(newJoiner, "gameState0", GetField(master, "gameState0"));
        SetField(newJoiner, "gameState1", GetField(master, "gameState1"));

        newJoiner.OnDeserialization();

        const int Hidden = -1;
        Assert.AreEqual(Hidden, GetField(newJoiner, "flop0"), "A dropped sync must render as hidden, never a live card value");
        Assert.AreEqual(Hidden, GetField(newJoiner, "flop1"));
        Assert.AreEqual(Hidden, GetField(newJoiner, "flop2"));
        Assert.AreEqual(Hidden, GetField(newJoiner, "turn"));
        Assert.AreEqual(Hidden, GetField(newJoiner, "river"));
    }

    // Three players already seated (master + two others) with a real hand mid-river,
    // correctly synced and displaying real board cards on every client. A fourth player
    // then joins the instance. This does not change who actually owns the table object,
    // but if a non-master seated client's own Networking.IsOwner(gameObject) read ever
    // misreports true for a tick (the kind of transient ownership-info hiccup that can
    // accompany a player-list change), Victim's own client -- despite never being the
    // real dealer -- takes the "new master without the deck" safety path and voids the
    // hand locally, corrupting the board cards it displays to itself.
    [Test]
    public void ExistingSeatedClientCorruptsBoardWhenOwnershipMisreadsTrueOnJoin()
    {
        StartAs(VictimId);
        var game = TableOwnedBy(Master);
        Sit(game, 0, Victim, 1000);
        Sit(game, 1, Attacker, 1000);
        Sit(game, 2, Bystander, 1000);

        // Victim's client already correctly caught up to a live hand with a real board.
        game.tableState = HoldemGame.TABLE_PLAYING;
        game.bettingRound = HoldemGame.RIVER;
        game.headsUp = false;
        game.playerState[0] = HoldemGame.PLAYER_COMMITED;
        game.playerState[1] = HoldemGame.PLAYER_COMMITED;
        game.playerState[2] = HoldemGame.PLAYER_DEAD;
        SetField(game, "flop0", 10);
        SetField(game, "flop1", 20);
        SetField(game, "flop2", 30);
        SetField(game, "turn", 40);
        SetField(game, "river", 50);
        game.aggressorSeat = -1;
        game.lastTransitionMillis = vrc.ServerTimeMillis;
        var lastBankBalances = (int[])GetField(game, "lastBankBalances");
        for (int i = 0; i < 3; i++)
        {
            game.wasSeated[i] = true;
            lastBankBalances[i] = 1000;
        }
        // Victim is a genuine non-owner who has already synced this state (mirrors
        // what OnDeserialization does on every real update they receive from the master).
        VrcRuntimeFake.InvokeNoArg(game, "OnDeserialization");
        Assert.AreEqual(10, GetField(game, "flop0"), "sanity: Victim is correctly showing the real board before the join");

        // A fourth player joins the instance. Nobody transferred ownership of the table --
        // simulate the hiccup where Victim's own IsOwner(gameObject) read misfires true
        // for a tick anyway.
        vrc.Owners[game.gameObject] = Victim;

        CallEitherName(game, "Transition");

        Assert.AreEqual(HoldemGame.TABLE_PLAYING, game.tableState,
            "A player merely joining the instance must not touch a hand Victim isn't dealing");
        Assert.AreEqual(10, GetField(game, "flop0"), "Victim's board must not be voided by a spurious ownership read");
    }
}
