#import <Foundation/Foundation.h>
#import <Security/Security.h>
#import <UIKit/UIKit.h>

extern "C" {

// 保存数据到 Keychain
bool SaveToKeychain(const char* key, const char* value) {
    NSString* keyString = [NSString stringWithUTF8String:key];
    NSString* valueString = [NSString stringWithUTF8String:value];

    NSData* valueData = [valueString dataUsingEncoding:NSUTF8StringEncoding];

    NSDictionary* query = @{
        (__bridge id)kSecClass : (__bridge id)kSecClassGenericPassword,
        (__bridge id)kSecAttrAccount : keyString,
    };

    SecItemDelete((__bridge CFDictionaryRef)query);

    NSDictionary* attributes = @{
        (__bridge id)kSecClass : (__bridge id)kSecClassGenericPassword,
        (__bridge id)kSecAttrAccount : keyString,
        (__bridge id)kSecValueData : valueData,
    };

    OSStatus status = SecItemAdd((__bridge CFDictionaryRef)attributes, NULL);
    return status == errSecSuccess;
}

// 从 Keychain 中获取数据
const char* GetFromKeychain(const char* key) {
    NSString* keyString = [NSString stringWithUTF8String:key];

    NSDictionary* query = @{
        (__bridge id)kSecClass : (__bridge id)kSecClassGenericPassword,
        (__bridge id)kSecAttrAccount : keyString,
        (__bridge id)kSecReturnData : @YES,
        (__bridge id)kSecMatchLimit : (__bridge id)kSecMatchLimitOne,
    };

    CFTypeRef result = NULL;
    OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, &result);

    if (status == errSecSuccess) {
        NSData* valueData = (__bridge_transfer NSData*)result;
        NSString* valueString = [[NSString alloc] initWithData:valueData encoding:NSUTF8StringEncoding];
        return strdup([valueString UTF8String]);
    }

    return NULL;
}

// 删除 Keychain 中的数据
bool DeleteFromKeychain(const char* key) {
    NSString* keyString = [NSString stringWithUTF8String:key];

    NSDictionary* query = @{
        (__bridge id)kSecClass : (__bridge id)kSecClassGenericPassword,
        (__bridge id)kSecAttrAccount : keyString,
    };

    OSStatus status = SecItemDelete((__bridge CFDictionaryRef)query);
    return status == errSecSuccess;
}
}