using Newtonsoft.Json;
using UnityEngine;

namespace YachtDice.Persistence
{
    public static class SaveSystem
    {
        private const string SaveKey = "YachtDice_SaveData";

        public static void Save(SaveData data)
        {
            string json = JsonConvert.SerializeObject(data, Formatting.Indented);
            PlayerPrefs.SetString(SaveKey, json);
            PlayerPrefs.Save();
        }

        public static SaveData Load()
        {
            if (!PlayerPrefs.HasKey(SaveKey))
                return new SaveData();

            string json = PlayerPrefs.GetString(SaveKey);

            try
            {
                return JsonConvert.DeserializeObject<SaveData>(json) ?? new SaveData();
            }
            catch (JsonException e)
            {
                Debug.LogWarning($"Failed to deserialize save data, returning default: {e.Message}");
                return new SaveData();
            }
        }

        public static void Delete()
        {
            PlayerPrefs.DeleteKey(SaveKey);
        }

        public static bool HasSave()
        {
            return PlayerPrefs.HasKey(SaveKey);
        }
    }
}
