using System;
using UnityEngine;

namespace CoolGameX
{
    /// <summary>
    /// Editor-only sign-in shared between the Setup window and Play Mode, stored in
    /// EditorPrefs (per machine and per project — never in your project files).
    /// Does nothing in builds.
    /// </summary>
    public static class EditorSession
    {
        [Serializable]
        public class Data
        {
            public string token;
            public long expiresAt;
            public string gameSlug;
            public string userId;
            public string email;
            public string username;
        }

        /// <summary>EditorPrefs key, scoped to this project folder.</summary>
        public static string Key => "CoolGameX.EditorSession::" + Application.dataPath;

        public static Data Load()
        {
#if UNITY_EDITOR
            var json = UnityEditor.EditorPrefs.GetString(Key, "");
            if (string.IsNullOrEmpty(json)) return null;
            try { return JsonUtility.FromJson<Data>(json); } catch { return null; }
#else
            return null;
#endif
        }

        public static void Save(Data data)
        {
#if UNITY_EDITOR
            if (data == null) UnityEditor.EditorPrefs.DeleteKey(Key);
            else UnityEditor.EditorPrefs.SetString(Key, JsonUtility.ToJson(data));
#endif
        }

        public static void Clear() => Save(null);

        /// <summary>True when a session exists and hasn't expired.</summary>
        public static bool IsValid(Data d) =>
            d != null && !string.IsNullOrEmpty(d.token) && d.expiresAt > DateTimeOffset.UtcNow.ToUnixTimeSeconds();

        /// <summary>The saved token for <paramref name="gameSlug"/>, or null.</summary>
        internal static string TokenFor(string gameSlug)
        {
            var d = Load();
            if (!IsValid(d)) return null;
            if (!string.IsNullOrEmpty(d.gameSlug) && !string.Equals(d.gameSlug, gameSlug, StringComparison.OrdinalIgnoreCase))
            {
                Log.Warn($"Your Editor sign-in is for \"{d.gameSlug}\", not \"{gameSlug}\". Sign in again from Tools > Cool GameX > Setup.");
                return null;
            }
            return d.token;
        }

        /// <summary>Keep the saved session current after the SDK refreshes the token in Play Mode.</summary>
        internal static void UpdateToken(string token, long expiresAt)
        {
            var d = Load();
            if (d == null) return;
            d.token = token;
            d.expiresAt = expiresAt;
            Save(d);
        }
    }
}
