using System;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;

namespace Davanci.Nexus
{
    // Posts free-text player feedback to Firebase Realtime Database via REST (no SDK).
    // Stored under /feedback with context attached; a text-free count goes to analytics.
    public static class NexusFeedback
    {
        [Serializable]
        class Payload
        {
            public string text;
            public string sentiment;
            public string game;
            public string version;
            public string platform;
            public string device;
            public string checkpoint;
            public long timestamp;
        }

        // Fire-and-forget. Empty text is ignored; requires NexusConfig.realtimeDbUrl.
        public static void Submit(string text, string sentiment = "negative", Action<bool> onDone = null)
        {
            if (string.IsNullOrWhiteSpace(text))
            {
                onDone?.Invoke(false);
                return;
            }

            string baseUrl = NexusConfig.Load()?.realtimeDbUrl;
            if (string.IsNullOrEmpty(baseUrl))
            {
                Debug.LogWarning("[Nexus] Feedback not sent, NexusConfig.realtimeDbUrl is empty.");
                onDone?.Invoke(false);
                return;
            }

            DavanciNexus.Custom("feedback_submitted", ("sentiment", sentiment));

            var payload = new Payload
            {
                text = text.Trim(),
                sentiment = sentiment,
                game = Application.productName,
                version = Application.version,
                platform = Application.platform.ToString(),
                device = SystemInfo.deviceModel,
                checkpoint = DavanciNexus.LastCheckpoint,
                timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
            };

            string url = baseUrl.TrimEnd('/') + "/feedback.json";
            byte[] body = Encoding.UTF8.GetBytes(JsonUtility.ToJson(payload));

            var req = new UnityWebRequest(url, UnityWebRequest.kHttpVerbPOST)
            {
                uploadHandler = new UploadHandlerRaw(body),
                downloadHandler = new DownloadHandlerBuffer(),
            };
            req.SetRequestHeader("Content-Type", "application/json");

            var op = req.SendWebRequest();
            op.completed += _ =>
            {
                bool ok = req.result == UnityWebRequest.Result.Success;
                if (ok)
                    Debug.Log("[Nexus] Feedback submitted.");
                else
                    Debug.LogWarning($"[Nexus] Feedback failed: {req.error}");

                req.Dispose();
                onDone?.Invoke(ok);
            };
        }
    }
}
