using UnityEditor;
using UnityEditor.PackageManager;
using UnityEditor.PackageManager.Requests;
using UnityEngine;

namespace Davanci.Nexus.Editor
{
    // Unity IAP ships as a UPM package (com.unity.purchasing), not a bundled .unitypackage,
    // so it installs differently from the SDKs in NexusInstaller: we add it to the project
    // manifest via the Package Manager client, then set the DAVANCI_IAP define once the
    // package's types are present (setting the define before that would break compilation).
    public static class NexusIapInstaller
    {
        public const string PackageId = "com.unity.purchasing";
        public const string Define = "DAVANCI_IAP";
        public const string ValidateDefine = "NEXUS_IAP_VALIDATE";

        // Unity IAP v5 (StoreController) — legacy IStoreController kept as fallback for detection.
        const string DetectTypeV5 = "UnityEngine.Purchasing.UnityIAPServices, UnityEngine.Purchasing";
        const string DetectTypeLegacy = "UnityEngine.Purchasing.IStoreController, UnityEngine.Purchasing";

        public static bool Installed =>
            NexusInstaller.TypeExists(DetectTypeV5) || NexusInstaller.TypeExists(DetectTypeLegacy);
        public static bool DefineSet => NexusInstaller.HasDefine(Define);
        public static bool ValidationEnabled => NexusInstaller.HasDefine(ValidateDefine);

        static AddRequest _add;

        // Kick off the UPM install. Unity fetches asynchronously; we poll and set the define
        // when it lands so Nexus' IAP provider starts compiling.
        public static void Install()
        {
            if (_add != null) return;
            _add = Client.Add(PackageId);
            EditorApplication.update += Poll;
        }

        static void Poll()
        {
            if (_add == null || !_add.IsCompleted) return;
            EditorApplication.update -= Poll;

            if (_add.Status == StatusCode.Success)
            {
                SetDefine(true);
                string ver = NexusPackageCatalog.Get("unity_iap")?.version
                    ?? NexusPackageCatalog.GetStatus("unity_iap").InstalledVersion;
                if (!string.IsNullOrEmpty(ver))
                    NexusPackageCatalog.StampInstalled("unity_iap", ver);
                Debug.Log("[Nexus] Unity IAP installed. DAVANCI_IAP set.");
                NexusIapPipeline.OnPackageInstalled();
                NexusSetupWindow.RefreshIfOpen();
                NexusDoctorWindow.RefreshIfOpen();
            }
            else
            {
                Debug.LogWarning($"[Nexus] Unity IAP install failed: {_add.Error?.message}. " +
                                 "Install it from Window → Package Manager (In-App Purchasing), then press Enable.");
            }
            _add = null;
        }

        public static void SetDefine(bool enabled) => NexusInstaller.SetDefine(Define, enabled);
        public static void SetValidation(bool enabled) => NexusInstaller.SetDefine(ValidateDefine, enabled);
    }
}
