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

namespace CoolGameX
{
    /// <summary>
    /// DLC ownership for the current game. Players get DLC by redeeming a code or
    /// buying it in the Cool GameX launcher; your game just checks:
    /// <code>
    /// if (await CoolAPI.DLC.Owns("haunted-expansion"))
    ///     UnlockExpansionContent();
    /// </code>
    /// </summary>
    public class DLC
    {
        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();
            return Array.IndexOf(owned, dlcSlug) >= 0;
        }

        /// <summary>
        /// Slugs of the DLC the player owns for this game. Cached after the first call;
        /// pass refresh:true to re-fetch (e.g. after the player buys something).
        /// </summary>
        public async Task<string[]> ListOwned(bool refresh = false)
        {
            if (cache != null && !refresh) return cache;
            var res = await Net.Get($"/api/dlc/owned?gameSlug={Json.Q(CoolAPI.GameSlug)}", auth: true);
            if (!res.Success) return cache ?? Array.Empty<string>();
            cache = Json.Parse<Dto.DlcOwned>(res.Body)?.owned ?? Array.Empty<string>();
            return cache;
        }

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

        internal void SetCache(string[] slugs) => cache = slugs ?? Array.Empty<string>();
    }
}
