// Native bridge for NexusICloudProvider — thin wrapper over NSUbiquitousKeyValueStore
// (iCloud Key-Value Store). Stores one opaque blob per player. Blobs cross to C# as
// base64 strings. _NexusICloudGet returns a strdup'd buffer because IL2CPP frees the
// returned char* after marshaling it to a string — returning anything not malloc'd
// (e.g. a static std::string's c_str) crashes with "pointer being freed was not allocated".
#import <Foundation/Foundation.h>
#include <string.h>

extern "C" {

    // KVS is usable only when the player is signed into iCloud.
    bool _NexusICloudAvailable() {
        return [[NSFileManager defaultManager] ubiquityIdentityToken] != nil;
    }

    void _NexusICloudSet(const char* key, const char* base64Value) {
        if (key == NULL) return;
        NSString* k = [NSString stringWithUTF8String:key];
        NSUbiquitousKeyValueStore* store = [NSUbiquitousKeyValueStore defaultStore];

        if (base64Value == NULL || base64Value[0] == '\0') {
            [store removeObjectForKey:k];
            return;
        }

        NSString* b64 = [NSString stringWithUTF8String:base64Value];
        NSData* data = [[NSData alloc] initWithBase64EncodedString:b64 options:0];
        if (data != nil) {
            [store setData:data forKey:k];
        }
    }

    // Caller (IL2CPP) frees the returned buffer, so it must be malloc'd — strdup does that.
    const char* _NexusICloudGet(const char* key) {
        if (key == NULL) return strdup("");

        NSString* k = [NSString stringWithUTF8String:key];
        NSData* data = [[NSUbiquitousKeyValueStore defaultStore] dataForKey:k];
        if (data == nil) return strdup("");

        NSString* b64 = [data base64EncodedStringWithOptions:0];
        return strdup([b64 UTF8String]);
    }

    bool _NexusICloudSynchronize() {
        return [[NSUbiquitousKeyValueStore defaultStore] synchronize];
    }
}
