#if UNITY_IOS && !UNITY_EDITOR
using System;
using System.Runtime.InteropServices;
using UnityEngine;

namespace Davanci.Nexus
{
    // iOS cloud slot via iCloud Key-Value Store (device builds only).
    public sealed class NexusICloudProvider : INexusCloudProvider
    {
        [DllImport("__Internal")] static extern bool _NexusICloudAvailable();
        [DllImport("__Internal")] static extern void _NexusICloudSet(string key, string base64Value);
        [DllImport("__Internal")] static extern string _NexusICloudGet(string key);
        [DllImport("__Internal")] static extern bool _NexusICloudSynchronize();

        readonly string _key = string.IsNullOrEmpty(Application.identifier)
            ? "nexus_save" : Application.identifier;

        public bool Available => _NexusICloudAvailable();

        public void Push(byte[] data, Action<bool> onDone)
        {
            try
            {
                if (!Available) { onDone?.Invoke(false); return; }
                _NexusICloudSet(_key, data == null ? "" : Convert.ToBase64String(data));
                bool ok = _NexusICloudSynchronize();
                onDone?.Invoke(ok);
            }
            catch (Exception e)
            {
                Debug.LogWarning($"[Nexus] iCloud push failed: {e.Message}");
                onDone?.Invoke(false);
            }
        }

        public void Pull(Action<bool, byte[]> onDone)
        {
            try
            {
                if (!Available) { onDone?.Invoke(false, null); return; }
                _NexusICloudSynchronize();
                string b64 = _NexusICloudGet(_key);
                byte[] data = string.IsNullOrEmpty(b64) ? null : Convert.FromBase64String(b64);
                onDone?.Invoke(true, data);
            }
            catch (Exception e)
            {
                Debug.LogWarning($"[Nexus] iCloud pull failed: {e.Message}");
                onDone?.Invoke(false, null);
            }
        }
    }
}
#endif
