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

public static class ApiService
{
    private const string BASE_URL = "http://127.0.0.1:8001";
    
    public static async Task<GameData> FetchUserGameData()
    {
        try
        {
            string url = $"{BASE_URL}/api/game/";
            
            using (UnityWebRequest request = UnityWebRequest.Get(url))
            {
                string token = PlayerPrefs.GetString("AuthToken");
                if (string.IsNullOrEmpty(token))
                {
                    Debug.LogError("No auth token found");
                    throw new UnauthorizedAccessException("No auth token found");
                }

                request.SetRequestHeader("Authorization", $"Token {token}");
                request.SetRequestHeader("Accept", "application/json");

                var operation = request.SendWebRequest();
                while (!operation.isDone)
                    await Task.Yield();

                Debug.Log($"Response Code: {request.responseCode}");
                Debug.Log($"Response: {request.downloadHandler.text}");
                
                if (request.result == UnityWebRequest.Result.Success)
                {
                    string jsonResponse = request.downloadHandler.text;
                    Debug.Log($"Received data: {jsonResponse}");
                    return JsonConvert.DeserializeObject<GameData>(jsonResponse);
                }
                else
                {
                    Debug.LogError($"API Error: {request.responseCode} - {request.error}");
                    throw new Exception($"Server error: {request.error}");
                }
            }
        }
        catch (Exception e)
        {
            Debug.LogError($"Failed to fetch game data: {e.Message}");
            throw;
        }
    }

    public static async Task SaveUserGameData(GameData gameData)
    {
        string token = PlayerPrefs.GetString("AuthToken");
        string jsonData = JsonConvert.SerializeObject(gameData);

        using (UnityWebRequest request = new UnityWebRequest($"{BASE_URL}/api/game/save", "POST"))
        {
            byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonData);
            request.uploadHandler = new UploadHandlerRaw(bodyRaw);
            request.downloadHandler = new DownloadHandlerBuffer();
            request.SetRequestHeader("Authorization", $"Token {token}");
            request.SetRequestHeader("Content-Type", "application/json");

            try
            {
                var operation = request.SendWebRequest();
                while (!operation.isDone)
                    await Task.Yield();

                if (request.result != UnityWebRequest.Result.Success)
                {
                    if (request.responseCode == 401)
                    {
                        throw new UnauthorizedAccessException("Authentication failed");
                    }
                    throw new Exception($"Failed to save: {request.error}");
                }
            }
            catch (Exception e)
            {
                Debug.LogError($"Failed to save game data: {e.Message}");
                throw;
            }
        }
    }
} 