using System;
using System.Threading.Tasks;
using UnityEngine;

namespace CoolGameX
{
    /// <summary>
    /// DLC ownership for the current game. Players acquire DLC by redeeming a
    /// code or buying it through the Cool GameX launcher; your game just checks
    /// ownership:
    /// <code>
    /// if (await CoolAPI.DLC.Owns("haunted-expansion"))
    ///     UnlockExpansionContent();
    /// </code>
    /// </summary>
    public class DLC
    {
        [Serializable]
        private class OwnedResponse { public string[] owned; }

        private string[] _cache;

        /// <summary>True if the player owns the given DLC (by slug).</summary>
        public async Task<bool> Owns(string dlcSlug)
        {
            if (string.IsNullOrEmpty(dlcSlug)) return false;
            var owned = await ListOwned();
            if (owned == null) return false;
            foreach (var s in owned)
                if (s == dlcSlug) return true;
            return false;
        }

        /// <summary>
        /// Returns the slugs of DLC the player owns for this game. Cached after
        /// the first call; pass refresh:true to re-fetch.
        /// </summary>
        public async Task<string[]> ListOwned(bool refresh = false)
        {
            if (_cache != null && !refresh) return _cache;

            var res = await Net.Get(
                $"/api/dlc/owned?gameSlug={Uri.EscapeDataString(CoolAPI.GameSlug)}",
                auth: true
            );
            if (!res.Success) return _cache ?? Array.Empty<string>();

            try
            {
                var parsed = JsonUtility.FromJson<OwnedResponse>(res.Body);
                _cache = parsed?.owned ?? Array.Empty<string>();
            }
            catch
            {
                _cache = Array.Empty<string>();
            }
            return _cache;
        }

        /// <summary>Clears the cached ownership list.</summary>
        public void ClearCache() => _cache = null;
    }
}
