using NUnit.Framework;
using UnityEngine;
using VRC.SDKBase;

/// <summary>
/// Regression tests for DunceCap pool identity.
///
/// The defect these lock down: the pool handed out caps by enumeration index and recorded
/// nothing, so DunceCapInteract resolved the wearer with Networking.GetOwner(gameObject).
/// Ownership of a pooled cap is never transferred to the wearer, so paying to remove a cap
/// targeted the scene's default owner (the master) rather than the person wearing it.
/// </summary>
public class DunceCapPoolTests
{
    private VrcRuntimeFake vrc;
    private GameObject poolGo;
    private DunceCapPool pool;
    private GameObject[] caps;
    private DunceCapInteract[] interacts;

    private const int CapCount = 4;

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

        poolGo = new GameObject("TestDunceCapPool");
        pool = poolGo.AddComponent<DunceCapPool>();

        caps = new GameObject[CapCount];
        interacts = new DunceCapInteract[CapCount];
        for (int i = 0; i < CapCount; i++)
        {
            // Mirror the real DunceCapPlayer prefab: the interactable sits on a "Hat"
            // child of the cap root, not on the root itself.
            caps[i] = new GameObject("Cap" + i);
            caps[i].transform.SetParent(poolGo.transform);
            var hat = new GameObject("Hat");
            hat.transform.SetParent(caps[i].transform);
            interacts[i] = hat.AddComponent<DunceCapInteract>();
        }
        pool.dunceCaps = caps;

        VrcRuntimeFake.InvokeNoArg(pool, "Start");
    }

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

    /// <summary>Drives the assignment pass directly, without needing head tracking data.</summary>
    private void Assign(params int[] wearerPlayerIds)
    {
        VrcRuntimeFake.SetPrivate(pool, "capPlayerIds", BuildAssignment(wearerPlayerIds));
    }

    private int[] BuildAssignment(int[] wearerPlayerIds)
    {
        var ids = new int[CapCount];
        for (int i = 0; i < CapCount; i++)
            ids[i] = i < wearerPlayerIds.Length ? wearerPlayerIds[i] : -1;
        return ids;
    }

    [Test]
    public void Pool_StartsWithNoSlotAssigned()
    {
        for (int i = 0; i < CapCount; i++)
            Assert.AreEqual(-1, pool.GetAssignedPlayerId(i), "slot " + i + " should start unassigned");
    }

    [Test]
    public void Pool_InitializesEachCapWithItsSlot()
    {
        // Each cap must know which slot it is, or it cannot resolve its wearer.
        for (int i = 0; i < CapCount; i++)
        {
            Assert.AreEqual(i, (int)VrcRuntimeFake.GetPrivate(interacts[i], "poolIndex"),
                "cap " + i + " did not receive its pool index");
            Assert.AreSame(pool, VrcRuntimeFake.GetPrivate(interacts[i], "pool"),
                "cap " + i + " did not receive its pool reference");
        }
    }

    [Test]
    public void GetAssignedPlayerId_IsOutOfRangeSafe()
    {
        Assert.AreEqual(-1, pool.GetAssignedPlayerId(-1));
        Assert.AreEqual(-1, pool.GetAssignedPlayerId(CapCount));
        Assert.AreEqual(-1, pool.GetAssignedPlayerId(9999));
    }

    [Test]
    public void Interact_ResolvesTheWearerNotTheNetworkOwner()
    {
        var bob = VrcRuntimeFake.MakePlayer(2, "Bob", false);
        var carol = VrcRuntimeFake.MakePlayer(3, "Carol", false);
        vrc.AddPlayer(bob);
        vrc.AddPlayer(carol);

        // Slot 0 is worn by Bob. The scene object's network owner remains Alice (the master),
        // which is exactly what the old code would have returned.
        Assign(bob.playerId);

        var wearer = interacts[0].GetWearer();

        Assert.IsNotNull(wearer, "slot 0 should resolve a wearer");
        Assert.AreEqual(bob.playerId, wearer.playerId,
            "wearer must come from the pool assignment, not Networking.GetOwner");
        Assert.AreNotEqual(vrc.LocalPlayer.playerId, wearer.playerId,
            "must not fall back to the master/local player");
    }

    [Test]
    public void Interact_ResolvesNothingForAnUnassignedSlot()
    {
        var bob = VrcRuntimeFake.MakePlayer(2, "Bob", false);
        vrc.AddPlayer(bob);
        Assign(bob.playerId);

        Assert.IsNull(interacts[1].GetWearer(), "an unassigned slot must not resolve a target");
        Assert.IsNull(interacts[3].GetWearer());
    }

    [Test]
    public void Interact_ResolvesNothingForAPlayerWhoLeft()
    {
        var bob = VrcRuntimeFake.MakePlayer(2, "Bob", false);
        vrc.AddPlayer(bob);
        Assign(bob.playerId);
        Assert.IsNotNull(interacts[0].GetWearer());

        // Bob leaves before the next assignment pass clears the slot.
        var list = (System.Collections.Generic.List<VRCPlayerApi>)
            typeof(VRCPlayerApi).GetField("sPlayers",
                System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public |
                System.Reflection.BindingFlags.NonPublic).GetValue(null);
        list.Remove(bob);

        Assert.IsNull(interacts[0].GetWearer(), "a stale slot must not resolve a departed player");
    }

    [Test]
    public void Interact_EachCapResolvesItsOwnDistinctWearer()
    {
        var bob = VrcRuntimeFake.MakePlayer(2, "Bob", false);
        var carol = VrcRuntimeFake.MakePlayer(3, "Carol", false);
        vrc.AddPlayer(bob);
        vrc.AddPlayer(carol);

        Assign(bob.playerId, carol.playerId);

        Assert.AreEqual(bob.playerId, interacts[0].GetWearer().playerId);
        Assert.AreEqual(carol.playerId, interacts[1].GetWearer().playerId);
    }
}
