using UnityEditor;

namespace Getly.Publisher
{
    /// <summary>
    /// Where the signed-in seller's key lives between editor sessions.
    ///
    /// EditorPrefs, not a file in the project. A key written under Assets/ gets
    /// committed, shared with collaborators, and — for a publisher of all
    /// people — exported inside their own .unitypackage and sold to strangers.
    /// EditorPrefs is per-machine and per-user, which is what a credential
    /// should be.
    /// </summary>
    public static class GetlySession
    {
        private const string KeyApiKey = "Getly.Publisher.ApiKey";
        private const string KeyStoreName = "Getly.Publisher.StoreName";
        private const string KeyStoreId = "Getly.Publisher.StoreId";
        private const string KeyBaseUrl = "Getly.Publisher.BaseUrl";

        public const string DefaultBaseUrl = "https://www.getly.store";

        public static string ApiKey
        {
            get => EditorPrefs.GetString(KeyApiKey, string.Empty);
            private set => EditorPrefs.SetString(KeyApiKey, value ?? string.Empty);
        }

        public static string StoreName => EditorPrefs.GetString(KeyStoreName, string.Empty);
        public static string StoreId => EditorPrefs.GetString(KeyStoreId, string.Empty);

        /// <summary>Overridable so the tool can be pointed at a local server during development.</summary>
        public static string BaseUrl
        {
            get => EditorPrefs.GetString(KeyBaseUrl, DefaultBaseUrl);
            set => EditorPrefs.SetString(KeyBaseUrl, string.IsNullOrEmpty(value) ? DefaultBaseUrl : value.TrimEnd('/'));
        }

        public static bool IsSignedIn => !string.IsNullOrEmpty(ApiKey);

        public static void SignIn(string apiKey, string storeId, string storeName)
        {
            ApiKey = apiKey;
            EditorPrefs.SetString(KeyStoreId, storeId ?? string.Empty);
            EditorPrefs.SetString(KeyStoreName, storeName ?? string.Empty);
        }

        public static void SignOut()
        {
            EditorPrefs.DeleteKey(KeyApiKey);
            EditorPrefs.DeleteKey(KeyStoreId);
            EditorPrefs.DeleteKey(KeyStoreName);
        }
    }
}
