using System.Threading.Tasks;
using UnityEngine;

namespace CoolGameX
{
    /// <summary>
    /// Playtime session tracking. Call <see cref="StartSession"/> when the game
    /// starts and <see cref="EndSession"/> on quit to report minutes played.
    /// </summary>
    public class Playtime
    {
        private float _sessionStart = -1f;
        private bool _active;

        /// <summary>Begins a playtime session.</summary>
        public void StartSession()
        {
            _sessionStart = Time.realtimeSinceStartup;
            _active = true;
            Debug.Log("[CoolAPI] Playtime session started.");
        }

        /// <summary>
        /// Ends the session and reports the elapsed minutes to the backend.
        /// Returns the number of minutes reported.
        /// </summary>
        public async Task<int> EndSession()
        {
            if (!_active)
                return 0;

            _active = false;
            float seconds = Time.realtimeSinceStartup - _sessionStart;
            int minutes = Mathf.Max(0, Mathf.RoundToInt(seconds / 60f));

            await ReportMinutes(minutes);
            Debug.Log($"[CoolAPI] Playtime session ended: {minutes} min.");
            return minutes;
        }

        /// <summary>
        /// Manually report a number of minutes (e.g. periodic heartbeats so
        /// playtime isn't lost if the game crashes before EndSession).
        /// </summary>
        public async Task<bool> ReportMinutes(int minutes)
        {
            if (minutes <= 0) return true;
            var json =
                $"{{\"gameSlug\":\"{CoolAPI.GameSlug}\",\"minutes\":{minutes}}}";
            var res = await Net.PostJson("/api/playtime/update", json);
            return res.Success;
        }
    }
}
