using System.IO;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;

namespace Davanci.Nexus.Editor
{
    // Toggles Unity Services → In-App Purchasing (ProjectSettings/UnityConnectSettings.asset)
    // when IAP is enabled in Nexus Setup — same switch as the Services window.
    public static class NexusUnityPurchasingServices
    {
        const string SettingsPath = "ProjectSettings/UnityConnectSettings.asset";
        static readonly Regex PurchasingEnabled = new Regex(
            @"(UnityPurchasingSettings:\s*\r?\n\s*m_Enabled:\s*)([01])",
            RegexOptions.Multiline);

        public static bool IsEnabled
        {
            get
            {
                if (!File.Exists(SettingsPath)) return false;
                var m = PurchasingEnabled.Match(File.ReadAllText(SettingsPath));
                return m.Success && m.Groups[2].Value == "1";
            }
        }

        public static void SetEnabled(bool enabled)
        {
            if (!File.Exists(SettingsPath))
            {
                Debug.LogWarning("[Nexus] UnityConnectSettings.asset not found — cannot enable Unity IAP service.");
                return;
            }

            string text = File.ReadAllText(SettingsPath);
            if (!PurchasingEnabled.IsMatch(text))
            {
                Debug.LogWarning("[Nexus] UnityPurchasingSettings block not found in UnityConnectSettings.");
                return;
            }

            string next = PurchasingEnabled.Replace(text, $"$1{(enabled ? 1 : 0)}");
            if (next == text) return;

            File.WriteAllText(SettingsPath, next);
            AssetDatabase.Refresh();
            Debug.Log($"[Nexus] Unity Services In-App Purchasing {(enabled ? "enabled" : "disabled")}.");
        }
    }
}
