using System;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;

namespace CoolGameX.Setup
{
    /// <summary>Minimal async HTTP for Editor tooling (works outside Play Mode).</summary>
    internal static class EditorHttp
    {
        internal class Response
        {
            public bool ok;
            public long status;
            public string body;
            public string error;
            public bool offline;
        }

        [Serializable] private class ErrorBody { public string error; }

        internal static Task<Response> Get(string url, string token = null) => Send("GET", url, null, token);
        internal static Task<Response> Post(string url, string json, string token = null) => Send("POST", url, json ?? "{}", token);

        private static Task<Response> Send(string method, string url, string json, string token)
        {
            var tcs = new TaskCompletionSource<Response>();
            UnityWebRequest req;
            try
            {
                req = new UnityWebRequest(url, method) { downloadHandler = new DownloadHandlerBuffer(), timeout = 20 };
            }
            catch (Exception e)
            {
                tcs.SetResult(new Response { error = e.Message });
                return tcs.Task;
            }
            if (json != null)
            {
                req.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(json));
                req.SetRequestHeader("Content-Type", "application/json");
            }
            req.SetRequestHeader("X-CGX-SDK", CoolAPI.Version + " editor");
            if (!string.IsNullOrEmpty(token)) req.SetRequestHeader("Authorization", "Bearer " + token);

            req.SendWebRequest().completed += _ =>
            {
                var r = new Response
                {
                    ok = req.result == UnityWebRequest.Result.Success,
                    status = req.responseCode,
                    body = req.downloadHandler?.text,
                    offline = req.result == UnityWebRequest.Result.ConnectionError,
                };
                if (!r.ok) r.error = ErrorOf(r.body) ?? req.error ?? "Request failed";
                req.Dispose();
                tcs.SetResult(r);
            };
            return tcs.Task;
        }

        private static string ErrorOf(string body)
        {
            if (string.IsNullOrEmpty(body) || body[0] != '{') return null;
            try { var e = JsonUtility.FromJson<ErrorBody>(body); return string.IsNullOrEmpty(e?.error) ? null : e.error; }
            catch { return null; }
        }
    }
}
