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

@implementation TurboNativeGoproxy
RCT_EXPORT_MODULE()

- (NSNumber *)multiply:(double)a b:(double)b {
    NSNumber *result = @(a * b);

    return result;
}

- (void)setSecureItem:(NSString *)key 
                value:(NSString *)value 
             resolver:(RCTPromiseResolveBlock)resolve 
             rejecter:(RCTPromiseRejectBlock)reject {
    
    NSData *valueData = [value dataUsingEncoding:NSUTF8StringEncoding];
    NSString *service = @"turbo-native-goproxy";
    
    // Create query dictionary
    NSDictionary *query = @{
        (__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,
        (__bridge id)kSecAttrService: service,
        (__bridge id)kSecAttrAccount: key,
        (__bridge id)kSecValueData: valueData,
        (__bridge id)kSecAttrAccessible: (__bridge id)kSecAttrAccessibleWhenUnlockedThisDeviceOnly
    };
    
    // First try to delete existing item
    SecItemDelete((__bridge CFDictionaryRef)@{
        (__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,
        (__bridge id)kSecAttrService: service,
        (__bridge id)kSecAttrAccount: key
    });
    
    // Add new item
    OSStatus status = SecItemAdd((__bridge CFDictionaryRef)query, NULL);
    
    if (status == errSecSuccess) {
        resolve(nil);
    } else {
        reject(@"KEYCHAIN_ERROR", [NSString stringWithFormat:@"Failed to store item: %d", (int)status], nil);
    }
}

- (void)getSecureItem:(NSString *)key 
             resolver:(RCTPromiseResolveBlock)resolve 
             rejecter:(RCTPromiseRejectBlock)reject {
    
    NSString *service = @"turbo-native-goproxy";
    
    NSDictionary *query = @{
        (__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,
        (__bridge id)kSecAttrService: service,
        (__bridge id)kSecAttrAccount: key,
        (__bridge id)kSecReturnData: @YES,
        (__bridge id)kSecMatchLimit: (__bridge id)kSecMatchLimitOne
    };
    
    CFTypeRef result = NULL;
    OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, &result);
    
    if (status == errSecSuccess) {
        NSData *data = (__bridge_transfer NSData *)result;
        NSString *value = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        resolve(value);
    } else if (status == errSecItemNotFound) {
        resolve(nil);
    } else {
        reject(@"KEYCHAIN_ERROR", [NSString stringWithFormat:@"Failed to retrieve item: %d", (int)status], nil);
    }
}

- (void)removeSecureItem:(NSString *)key 
                resolver:(RCTPromiseResolveBlock)resolve 
                rejecter:(RCTPromiseRejectBlock)reject {
    
    NSString *service = @"turbo-native-goproxy";
    
    NSDictionary *query = @{
        (__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,
        (__bridge id)kSecAttrService: service,
        (__bridge id)kSecAttrAccount: key
    };
    
    OSStatus status = SecItemDelete((__bridge CFDictionaryRef)query);
    
    if (status == errSecSuccess || status == errSecItemNotFound) {
        resolve(nil);
    } else {
        reject(@"KEYCHAIN_ERROR", [NSString stringWithFormat:@"Failed to remove item: %d", (int)status], nil);
    }
}

- (void)hasSecureItem:(NSString *)key 
             resolver:(RCTPromiseResolveBlock)resolve 
             rejecter:(RCTPromiseRejectBlock)reject {
    
    NSString *service = @"turbo-native-goproxy";
    
    NSDictionary *query = @{
        (__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,
        (__bridge id)kSecAttrService: service,
        (__bridge id)kSecAttrAccount: key,
        (__bridge id)kSecMatchLimit: (__bridge id)kSecMatchLimitOne
    };
    
    OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, NULL);
    
    if (status == errSecSuccess) {
        resolve(@YES);
    } else if (status == errSecItemNotFound) {
        resolve(@NO);
    } else {
        reject(@"KEYCHAIN_ERROR", [NSString stringWithFormat:@"Failed to check item: %d", (int)status], nil);
    }
}

- (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:
    (const facebook::react::ObjCTurboModule::InitParams &)params
{
    return std::make_shared<facebook::react::NativeTurboNativeGoproxySpecJSI>(params);
}

@end
