using NUnit.Framework;
using UnityEngine;

public class BalanceComponentTests
{
    private GameObject balanceGo;
    private PlayerBalanceComponent balanceComponent;

    [SetUp]
    public void SetUp()
    {
        balanceGo = new GameObject("TestPlayerBalance");
        balanceComponent = balanceGo.AddComponent<PlayerBalanceComponent>();
        balanceComponent.CurrentSyncedBalance = 1000;
        
        var isReadyField = typeof(PlayerBalanceComponent).GetField("bIsReady", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        isReadyField.SetValue(balanceComponent, true);
    }

    [TearDown]
    public void TearDown()
    {
        Object.DestroyImmediate(balanceGo);
    }

    [Test]
    public void TestBalanceComponent_IsReadyWhenInitialized()
    {
        Assert.IsTrue(balanceComponent.IsReady(), "Balance component should be ready when bIsReady=true and CurrentSyncedBalance >= 0");
        Assert.AreEqual(1000, balanceComponent.GetBalance());
    }

    [Test]
    public void TestBalanceComponent_ModifyBalancePositiveAndNegative()
    {
        balanceComponent.ModifyBalance(500);
        Assert.AreEqual(1500, balanceComponent.GetBalance(), "ModifyBalance(500) should increase balance to 1500");

        balanceComponent.ModifyBalance(-200);
        Assert.AreEqual(1300, balanceComponent.GetBalance(), "ModifyBalance(-200) should decrease balance to 1300");
    }

    [Test]
    public void TestBalanceComponent_ModifyBalancePreventsNegative()
    {
        balanceComponent.ModifyBalance(-2000);
        Assert.AreEqual(0, balanceComponent.GetBalance(), "ModifyBalance deducting more than current balance should clamp to 0, not negative");
    }

    private int SubscriberCount()
    {
        return (int)typeof(PlayerBalanceComponent)
            .GetField("subscriberCount", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)
            .GetValue(balanceComponent);
    }

    [Test]
    public void TestBalanceComponent_SubscribeAndUnsubscribe()
    {
        var first = new GameObject("Subscriber0").AddComponent<HoldemPlayer>();
        var second = new GameObject("Subscriber1").AddComponent<HoldemPlayer>();

        Assert.AreEqual(0, SubscriberCount());

        balanceComponent.SubscribeToBalanceChanges(first);
        balanceComponent.SubscribeToBalanceChanges(second);
        Assert.AreEqual(2, SubscriberCount(), "Both subscribers should be registered");

        // Unsubscribe swaps the last entry into the freed slot; the survivor must still be there.
        balanceComponent.UnsubscribeFromBalanceChanges(first);
        Assert.AreEqual(1, SubscriberCount(), "Unsubscribing should drop exactly one subscriber");

        balanceComponent.UnsubscribeFromBalanceChanges(second);
        Assert.AreEqual(0, SubscriberCount());

        Object.DestroyImmediate(first.gameObject);
        Object.DestroyImmediate(second.gameObject);
    }

    [Test]
    public void TestBalanceComponent_UnsubscribeUnknownSubscriberIsNoOp()
    {
        var subscribed = new GameObject("Subscriber").AddComponent<HoldemPlayer>();
        var stranger = new GameObject("Stranger").AddComponent<HoldemPlayer>();

        balanceComponent.SubscribeToBalanceChanges(subscribed);
        balanceComponent.UnsubscribeFromBalanceChanges(stranger);

        Assert.AreEqual(1, SubscriberCount(), "Unsubscribing something that never subscribed must not evict anyone");

        Object.DestroyImmediate(subscribed.gameObject);
        Object.DestroyImmediate(stranger.gameObject);
    }

    [Test]
    public void TestBalanceComponent_SubscriberListDoesNotOverflow()
    {
        // The backing array is fixed at 10; extra subscribers are dropped rather than
        // writing out of bounds.
        var subscribers = new HoldemPlayer[15];
        for (int i = 0; i < subscribers.Length; i++)
        {
            subscribers[i] = new GameObject("Subscriber_" + i).AddComponent<HoldemPlayer>();
            balanceComponent.SubscribeToBalanceChanges(subscribers[i]);
        }

        Assert.AreEqual(10, SubscriberCount(), "Subscriber count should cap at the array size");

        for (int i = 0; i < subscribers.Length; i++)
        {
            Object.DestroyImmediate(subscribers[i].gameObject);
        }
    }

    [Test]
    public void TestBalanceComponent_NotReadyBalanceIsRefused()
    {
        var pendingGo = new GameObject("PendingBalance");
        var pending = pendingGo.AddComponent<PlayerBalanceComponent>();
        // Default state: bIsReady false, CurrentSyncedBalance -1.
        Assert.IsFalse(pending.IsReady(), "A component that has never synced is not ready");

        UnityEngine.TestTools.LogAssert.Expect(LogType.Error, "PlayerBalanceComponent::GetBalance() WAS CALLED BEFORE IT WAS READY.");
        Assert.AreEqual(-1, pending.GetBalance(), "GetBalance before ready should report -1, not a bogus 0");

        UnityEngine.TestTools.LogAssert.Expect(LogType.Error, "PlayerBalanceComponent::ModifyBalance() WAS CALLED FROM BEFORE IT WAS READY.");
        pending.ModifyBalance(500);
        Assert.AreEqual(-1, pending.CurrentSyncedBalance, "ModifyBalance before ready must not touch the balance");

        Object.DestroyImmediate(pendingGo);
    }

    [Test]
    public void TestBalanceComponent_ProfitAccumulates()
    {
        Assert.AreEqual(0, balanceComponent.GetProfit(), "Profit starts at zero");

        balanceComponent.RecordProfit(250);
        balanceComponent.RecordProfit(-100);

        Assert.AreEqual(150, balanceComponent.GetProfit(), "Profit should be the running sum of recorded deltas");

        // Profit is bookkeeping only; it must not move the balance on its own.
        Assert.AreEqual(1000, balanceComponent.GetBalance(), "RecordProfit should not change the balance");
    }
}
