using System.Threading.Tasks;
using UnityEngine;

namespace CoolGameX
{
    /// <summary>Authentication. The token comes from the Cool GameX launcher.</summary>
    public class Auth
    {
        /// <summary>
        /// Logs in using a Supabase JWT (typically the token saved/passed by the
        /// launcher). Verifies it against the backend before storing it.
        /// </summary>
        public async Task<bool> LoginWithToken(string token)
        {
            if (string.IsNullOrEmpty(token))
            {
                Debug.LogWarning("[CoolAPI] LoginWithToken called with empty token.");
                return false;
            }

            // Temporarily set the token so the verification call is authenticated.
            CoolAPI.Token = token;

            // /api/health doesn't need auth; we validate by hitting an authed
            // endpoint that simply echoes success — the library list.
            var res = await Net.Get("/api/library", auth: true);
            if (!res.Success)
            {
                Debug.LogWarning("[CoolAPI] Token rejected by server.");
                CoolAPI.Token = null;
                return false;
            }

            Debug.Log("[CoolAPI] Logged in.");
            return true;
        }

        /// <summary>Clears the stored token.</summary>
        public void Logout()
        {
            CoolAPI.Token = null;
        }
    }
}
