#import "CROSSxKeychainBridge.h"
#import <Security/Security.h>

static NSString* const kServiceName = @"com.crossx.sdk.unity";

static NSString* ToNSString(const char* cStr) {
    return cStr ? [NSString stringWithUTF8String:cStr] : nil;
}

static NSMutableDictionary* BaseQuery(NSString* key) {
    return [@{
        (__bridge id)kSecClass:       (__bridge id)kSecClassGenericPassword,
        (__bridge id)kSecAttrService: kServiceName,
        (__bridge id)kSecAttrAccount: key
    } mutableCopy];
}

extern "C" {

void CROSSxKeychain_Save(const char* key, const char* value) {
    NSString* nsKey   = ToNSString(key);
    NSString* nsValue = ToNSString(value);
    if (!nsKey || !nsValue) return;

    NSData* data = [nsValue dataUsingEncoding:NSUTF8StringEncoding];

    // Remove the existing item before adding a new one (simpler than update)
    NSMutableDictionary* query = BaseQuery(nsKey);
    SecItemDelete((__bridge CFDictionaryRef)query);

    query[(__bridge id)kSecValueData]      = data;
    query[(__bridge id)kSecAttrAccessible]  =
        (__bridge id)kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly;

    OSStatus status = SecItemAdd((__bridge CFDictionaryRef)query, NULL);
    if (status != errSecSuccess) {
        NSLog(@"[CROSSxKeychain] Save failed (key=%@, status=%d)", nsKey, (int)status);
    }
}

const char* CROSSxKeychain_Load(const char* key) {
    NSString* nsKey = ToNSString(key);
    if (!nsKey) return NULL;

    NSMutableDictionary* query = BaseQuery(nsKey);
    query[(__bridge id)kSecReturnData] = @YES;
    query[(__bridge id)kSecMatchLimit] = (__bridge id)kSecMatchLimitOne;

    CFDataRef dataRef = NULL;
    OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query,
                                          (CFTypeRef*)&dataRef);
    if (status != errSecSuccess || !dataRef) return NULL;

    NSData*   data  = (__bridge_transfer NSData*)dataRef;
    NSString* value = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    return value ? strdup([value UTF8String]) : NULL;
}

void CROSSxKeychain_Delete(const char* key) {
    NSString* nsKey = ToNSString(key);
    if (!nsKey) return;

    NSMutableDictionary* query = BaseQuery(nsKey);
    SecItemDelete((__bridge CFDictionaryRef)query);
}

bool CROSSxKeychain_Has(const char* key) {
    NSString* nsKey = ToNSString(key);
    if (!nsKey) return false;

    NSMutableDictionary* query = BaseQuery(nsKey);
    OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, NULL);
    return status == errSecSuccess;
}

} // extern "C"
