using System.Collections;
using System.Net;
using UnityEngine;
using UnityEngine.Networking;

public class NetworkDiagnostic : MonoBehaviour
{
    void Start()
    {
        StartCoroutine(RunDiagnostics());
    }

    IEnumerator RunDiagnostics()
    {
        Debug.Log("🌐 Starting network diagnostics...");

        // 1. UnityWebRequest to Google (HTTP check)
        string testUrl = "https://www.google.com";
        using (UnityWebRequest request = UnityWebRequest.Get(testUrl))
        {
            yield return request.SendWebRequest();

            if (request.result != UnityWebRequest.Result.Success)
                Debug.LogError($"❌ Google request failed: {request.error}");
            else
                Debug.Log("✅ Google request succeeded.");
        }

        // 2. DNS Resolution (System.Net)
        string hostToCheck = "www.google.com";
        try
        {
            Debug.Log($"🔎 Attempting DNS resolution for: {hostToCheck}");
            IPAddress[] addresses = Dns.GetHostAddresses(hostToCheck);
            foreach (var addr in addresses)
                Debug.Log($"✅ DNS Resolved: {addr}");
        }
        catch (System.Exception ex)
        {
            Debug.LogError($"❌ DNS resolution failed: {ex.Message}");
        }

        // 3. UnityWebRequest to Supabase Health
        string supabaseHealth = "https://cezghxztvyggwgunyhmq.supabase.co/auth/v1/health";
        using (UnityWebRequest supa = UnityWebRequest.Get(supabaseHealth))
        {
            supa.SetRequestHeader("apikey", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImNlemdoeHp0dnlnZ3dndW55aG1xIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDcyMTk5MzcsImV4cCI6MjA2Mjc5NTkzN30.vr6-3X3Ux_DjcCiw_CqG-VKP8BiBXtmCzAXjYTiA_vY");
            yield return supa.SendWebRequest();

            if (supa.result != UnityWebRequest.Result.Success)
                Debug.LogError($"❌ Supabase health check failed: {supa.error}");
            else
                Debug.Log($"✅ Supabase responded: {supa.downloadHandler.text}");
        }

        Debug.Log("📊 Network diagnostics complete.");
    }
}
