using UnityEditor;
using UnityEngine;

namespace Davanci.Nexus.Editor
{
    // Auto-enables NEXUS_IAP_VALIDATE when Unity's receipt-validation tangle files are present
    // (AppleTangle.cs / GooglePlayTangle.cs from Services → In-App Purchasing → Receipt Validation
    // Obfuscator). Clears the define when they're removed so builds compile cleanly.
    [InitializeOnLoad]
    public static class NexusIapValidationInstaller
    {
        public const string AppleTangleClass = "AppleTangle";
        public const string GoogleTangleClass = "GooglePlayTangle";

        static NexusIapValidationInstaller()
        {
            EditorApplication.delayCall += Sync;
        }

        public static bool TanglesPresent =>
            FindTangleScript(AppleTangleClass) != null || FindTangleScript(GoogleTangleClass) != null;

        public static bool AppleTanglePresent => FindTangleScript(AppleTangleClass) != null;
        public static bool GoogleTanglePresent => FindTangleScript(GoogleTangleClass) != null;

        public static string FindTangleScript(string className)
        {
            foreach (var guid in AssetDatabase.FindAssets($"{className} t:Script"))
            {
                var path = AssetDatabase.GUIDToAssetPath(guid);
                if (path.EndsWith(className + ".cs"))
                    return path;
            }
            return null;
        }

        public static void Sync()
        {
            if (!NexusIapInstaller.Installed) return;
            // AppleTangle is auto-generated when IAP is enabled; Google is optional (Android).
            NexusIapInstaller.SetValidation(AppleTanglePresent);
        }
    }
}
