// Copyright (c) 2026 EzAdmin. All rights reserved.
// Licensed under the EzAdmin Client License. See LICENSE-CLIENT.txt.

using EzAdmin.Client;
using PlayFab;
using PlayFab.ClientModels;
using UnityEngine;

namespace EzAdmin.Samples
{
    [AddComponentMenu("EzAdmin/Samples/EzAdmin Samples")]
    public sealed class EzAdminSamples : MonoBehaviour
    {

        private EzSecureInt _coins = 100;
        private EzSecureFloat _health = 100f;

        private void OnEnable()
        {

            EzAdminClient.EventChanged += OnEventChanged;

            EzAdminClient.FreezeChanged += OnFreezeChanged;

            EzAdminAntiCheat.Detected += OnCheatDetected;
        }

        private void OnDisable()
        {
            EzAdminClient.EventChanged -= OnEventChanged;
            EzAdminClient.FreezeChanged -= OnFreezeChanged;
            EzAdminAntiCheat.Detected -= OnCheatDetected;
        }

        public void AddReward(int baseAmount)
        {
            _coins += Mathf.RoundToInt(baseAmount * EzAdminClient.Multiplier);
        }

        public void TakeDamage(float amount)
        {
            _health = Mathf.Max(0f, _health - amount);
        }

        public void BuyItem(string itemId, int price, string currencyCode)
        {
            PlayFabClientAPI.PurchaseItem(new PurchaseItemRequest
            {
                ItemId = itemId,
                Price = price,
                VirtualCurrency = currencyCode,
            }, result =>
            {
                if (result.Items != null && result.Items.Count > 0)
                    EzAdminClient.Instance.ReportPurchase(result.Items[0].ItemInstanceId);
            }, error => Debug.LogWarning(error.GenerateErrorReport()));
        }

        public void Gift(string friendPlayFabId, int amount)
        {
            EzAdminClient.Instance.SendCurrency(friendPlayFabId, amount, "a gift", (ok, message) =>
                Debug.Log(ok ? "Sent." : "Not sent: " + message));
        }

        public void ImpossibleScore(int score)
        {
            if (score > 1_000_000) EzAdminAntiCheat.Report("score " + score + " in one round");
        }

        private static void OnEventChanged() =>
            Debug.Log(EzAdminClient.EventName == "" ? "No live event." : $"{EzAdminClient.EventName}: x{EzAdminClient.Multiplier}");

        private static void OnFreezeChanged(bool frozen) =>
            Debug.Log(frozen ? "Frozen by a moderator." : "Free to move.");

        private static void OnCheatDetected(string check, string detail) =>
            Debug.LogWarning($"Anti tamper: {check} ({detail})");
    }
}
