using NUnit.Framework;
using UnityEngine;
using UdonChipsHat;

/// <summary>
/// Regression tests for UdonChipsHat persistence.
///
/// The defect these lock down: HatManager.OnDeserialization used to write the master's
/// (empty) hat slot straight back into the local player's PlayerData. When that landed
/// before HatPlayerData.OnPlayerRestored read the same keys, the saved hat was erased and
/// never requested - so a hat "sometimes" vanished between sessions depending purely on
/// network timing.
/// </summary>
public class HatPersistenceTests
{
    private const string TypeKey = "UdonChipsHat/Type";
    private const string GiverKey = "UdonChipsHat/Giver";
    private const string HasHatKey = "UdonChipsHat/HasHat";

    private const int LocalId = 5;

    private VrcRuntimeFake vrc;
    private GameObject managerGo;
    private GameObject playerDataGo;
    private HatManager manager;
    private HatPlayerData playerData;

    [SetUp]
    public void SetUp()
    {
        vrc = new VrcRuntimeFake();
        vrc.Install(LocalId, "Bob");

        managerGo = new GameObject("TestHatManager");
        playerDataGo = new GameObject("TestHatPlayerData");
        manager = managerGo.AddComponent<HatManager>();
        playerData = playerDataGo.AddComponent<HatPlayerData>();
        playerData.hatManager = manager;
    }

    [TearDown]
    public void TearDown()
    {
        Object.DestroyImmediate(managerGo);
        Object.DestroyImmediate(playerDataGo);
        vrc.Uninstall();
    }

    /// <summary>Bob saved a hat in a previous session.</summary>
    private void SeedSavedHat(byte type = 3, string giver = "Alice")
    {
        vrc.SeedInt(TypeKey, type);
        vrc.SeedString(GiverKey, giver);
        vrc.SeedInt(HasHatKey, 1);
    }

    private void StartManager()
    {
        VrcRuntimeFake.InvokeNoArg(manager, "Start");
    }

    private void Deserialize()
    {
        VrcRuntimeFake.InvokeNoArg(manager, "OnDeserialization");
    }

    private void Restore()
    {
        playerData.OnPlayerRestored(vrc.LocalPlayer);
    }

    /// <summary>We own our player object, but somebody else owns the HatManager.</summary>
    private void MasterUnreachable()
    {
        vrc.IsOwnerOf = go => go != managerGo;
    }

    /// <summary>We are the master again.</summary>
    private void MasterReachable()
    {
        vrc.IsOwnerOf = null;
    }

    // ---------------------------------------------------------------- the race

    [Test]
    public void Restore_SurvivesWhenDeserializationArrivesFirst()
    {
        SeedSavedHat();
        StartManager();

        // The losing order pre-fix: master's empty state lands before we read persistence.
        Deserialize();
        Restore();

        Assert.AreEqual(1, vrc.GetInt(HasHatKey),
            "Persisted HasHat must not be erased by a deserialization that precedes the restore.\nWrites:\n  " + vrc.WriteLog());
        Assert.IsTrue(manager.PlayerHasHats[LocalId],
            "Hat should have been requested and applied.\nWrites:\n  " + vrc.WriteLog());
    }

    [Test]
    public void Restore_SucceedsWhenRestoreRunsFirst()
    {
        SeedSavedHat();
        StartManager();

        Restore();
        Deserialize();

        Assert.AreEqual(1, vrc.GetInt(HasHatKey));
        Assert.IsTrue(manager.PlayerHasHats[LocalId]);
    }

    [Test]
    public void Deserialization_WritesNothingBeforeRestoreCompletes()
    {
        SeedSavedHat();
        StartManager();
        vrc.ClearWrites();

        Deserialize();
        Deserialize();

        Assert.IsEmpty(vrc.Writes,
            "OnDeserialization must not touch PlayerData until the restore is reconciled, got:\n  " + vrc.WriteLog());
    }

    [Test]
    public void Deserialization_DoesNotRewriteUnchangedState()
    {
        SeedSavedHat();
        StartManager();
        Restore();
        vrc.ClearWrites();

        // Any hat change by any other player re-fires OnDeserialization on every client.
        Deserialize();
        Deserialize();
        Deserialize();

        Assert.IsEmpty(vrc.Writes,
            "Repeated identical state must not rewrite persistence, got:\n  " + vrc.WriteLog());
    }

    [Test]
    public void Deserialization_PersistsAGenuineChange()
    {
        SeedSavedHat();
        StartManager();
        Restore();
        vrc.ClearWrites();

        // Master removes Bob's hat; the change must reach persistence.
        manager.PlayerHasHats[LocalId] = false;
        manager.PlayerHatTypes[LocalId] = 0;
        manager.PlayerGiverNames[LocalId] = "";
        Deserialize();

        Assert.AreEqual(0, vrc.GetInt(HasHatKey), "A real state change must be persisted.");
        Assert.IsNotEmpty(vrc.Writes);
    }

    [Test]
    public void NoSavedHat_MarksRestoreCompleteWithoutRequesting()
    {
        // Fresh player, no keys at all.
        StartManager();
        Restore();

        Assert.IsTrue(manager.IsPersistenceRestoreComplete(),
            "A player with no saved hat is already reconciled.");
        Assert.IsFalse(manager.PlayerHasHats[LocalId]);
    }

    // ---------------------------------------------------------------- Start() clobber

    [Test]
    public void Start_DoesNotClobberAlreadyReceivedSyncedState()
    {
        // Late joiner: OnDeserialization delivered state before Start() ran.
        manager.PlayerHatTypes = new byte[manager.maxPlayers];
        manager.PlayerHasHats = new bool[manager.maxPlayers];
        manager.PlayerGiverNames = new string[manager.maxPlayers];
        manager.PlayerHasHats[LocalId] = true;
        manager.PlayerHatTypes[LocalId] = 3;
        manager.PlayerGiverNames[LocalId] = "Alice";

        StartManager();

        Assert.IsTrue(manager.PlayerHasHats[LocalId], "Start() must not discard received synced state");
        Assert.AreEqual(3, manager.PlayerHatTypes[LocalId]);
        Assert.AreEqual("Alice", manager.PlayerGiverNames[LocalId]);
    }

    [Test]
    public void Start_AllocatesArraysWhenAbsent()
    {
        StartManager();

        Assert.IsNotNull(manager.PlayerHasHats);
        Assert.AreEqual(manager.maxPlayers, manager.PlayerHasHats.Length);
        Assert.AreEqual(manager.maxPlayers, manager.PlayerHatTypes.Length);
        Assert.AreEqual(manager.maxPlayers, manager.PlayerGiverNames.Length);
    }

    // ---------------------------------------------------------------- master guards

    [Test]
    public void MasterApplyHat_RejectsOutOfRangePlayerId()
    {
        StartManager();

        manager.MasterApplyHat(-1, 2, "Alice");
        manager.MasterApplyHat(manager.maxPlayers, 2, "Alice");

        for (int i = 0; i < manager.maxPlayers; i++)
            Assert.IsFalse(manager.PlayerHasHats[i], "No slot should have been touched");
    }

    [Test]
    public void MasterApplyHat_DoesNotOverwriteAnExistingHat()
    {
        StartManager();
        manager.MasterApplyHat(7, 2, "Alice");
        manager.MasterApplyHat(7, 9, "Carol");

        Assert.AreEqual(2, manager.PlayerHatTypes[7], "First hat must win");
        Assert.AreEqual("Alice", manager.PlayerGiverNames[7]);
    }

    [Test]
    public void MasterRemoveHat_ClearsTypeGiverAndFlag()
    {
        StartManager();
        manager.MasterApplyHat(7, 2, "Alice");
        manager.MasterRemoveHat(7);

        Assert.IsFalse(manager.PlayerHasHats[7]);
        Assert.AreEqual(0, manager.PlayerHatTypes[7]);
        Assert.AreEqual("", manager.PlayerGiverNames[7]);
    }

    [Test]
    public void RemovalIsPersistedEvenIfRestoreNeverReconciled()
    {
        // Master never acknowledges the restore...
        SeedSavedHat();
        StartManager();
        MasterUnreachable();
        Restore();

        Assert.IsFalse(manager.IsPersistenceRestoreComplete(),
            "An unconfirmed restore must not mark itself reconciled");
        Assert.AreEqual(1, vrc.GetInt(HasHatKey), "...and must leave the saved hat intact");

        // ...but a hat the player deliberately pays to remove must still stick.
        MasterReachable();
        manager.MasterApplyHat(LocalId, 3, "Alice");
        manager.MasterRemoveHat(LocalId);

        Assert.AreEqual(0, vrc.GetInt(HasHatKey),
            "A deliberate removal must persist regardless of restore state.\nWrites:\n  " + vrc.WriteLog());
    }

    // ------------------------------------------------- sync-driven confirmation

    [Test]
    public void Restore_IsConfirmedByTheSyncedState_NotByPolling()
    {
        SeedSavedHat();
        StartManager();

        // We are not the master, so RequestApplyHat forwards and nothing lands yet.
        MasterUnreachable();
        Restore();

        Assert.IsFalse(manager.IsPersistenceRestoreComplete(),
            "Restore must stay open until the master's state confirms the hat");

        // The master applies it and serializes; that reaches us as an ordinary sync.
        manager.PlayerHasHats[LocalId] = true;
        manager.PlayerHatTypes[LocalId] = 3;
        manager.PlayerGiverNames[LocalId] = "Alice";
        Deserialize();

        Assert.IsTrue(manager.IsPersistenceRestoreComplete(),
            "A deserialization showing our hat must complete the restore");
        Assert.AreEqual(1, vrc.GetInt(HasHatKey));
    }

    [Test]
    public void LostRequest_LeavesSavedHatIntactAndRestoreOpen()
    {
        SeedSavedHat();
        StartManager();
        MasterUnreachable();
        Restore();

        // Master never applies it; other players' hat changes keep arriving.
        Deserialize();
        Deserialize();

        Assert.IsFalse(manager.IsPersistenceRestoreComplete(),
            "An unconfirmed restore must not mark itself reconciled");
        Assert.AreEqual(1, vrc.GetInt(HasHatKey),
            "A lost request must never cost the player their saved hat.\nWrites:\n  " + vrc.WriteLog());
    }
}
