//
//  TrustDeviceSe.m
//  TrustDeviceReactNative
//
//  Created on 2025.11.12
//

#import "TrustDeviceSe.h"
#import <React/RCTLog.h>
#import <React/RCTConvert.h>
#import <TDMobRisk/TDMobRisk.h>

@implementation TrustDeviceSe

RCT_EXPORT_MODULE();


RCT_REMAP_METHOD(getSDKVersion,
                 getSDKVersionResolver:(RCTPromiseResolveBlock)resolve
                 rejecter:(RCTPromiseRejectBlock)reject)
{
  TDDeviceManager_t *manager = [TDDeviceManager sharedManager];
  NSString* version = manager->getSDKVersion();
  resolve(version);
}

RCT_EXPORT_METHOD(initWithOptions:(NSDictionary*)options)
{
  NSMutableDictionary* mutableOptions = [options mutableCopy];
  mutableOptions[@"allowd"] = options[@"debug"];
  TDDeviceManager_t *manager = [TDDeviceManager sharedManager];
  manager->initWithOptions([mutableOptions copy]);
}

RCT_REMAP_METHOD(getDeviceInfo,
                 getDeviceInfoResolver:(RCTPromiseResolveBlock)resolve
                 rejecter:(RCTPromiseRejectBlock)reject)
{
    TDDeviceManager_t *manager = [TDDeviceManager sharedManager];
    manager->getDeviceInfo(^(TDDeviceResponse response){
        int code = response.apiStatus.code;
        int deviceRiskScore = response.deviceRiskScore;
        
        
        NSString* fpVersion = @"";
        NSString* blackBox = @"";
        NSString* anonymousId = @"";
        NSString* message = @"";
        NSString* sealedResult = @"";
        
        if(code == 0) {
            
            fpVersion = response.fpVersion ? [NSString stringWithUTF8String:response.fpVersion] : @"";
            blackBox = response.blackBox ? [NSString stringWithUTF8String:response.blackBox] : @"";
            anonymousId = response.anonymousId ? [NSString stringWithUTF8String:response.anonymousId] : @"";
            sealedResult = response.sealedResult ? [NSString stringWithUTF8String:response.sealedResult] : @"";
            message = response.apiStatus.message ? [NSString stringWithUTF8String:response.apiStatus.message] : @"";
        } else {
            message = response.apiStatus.message ? [NSString stringWithUTF8String:response.apiStatus.message] : @"";
        }
        
        // 创建结果字典
        NSMutableDictionary *resultDict = [NSMutableDictionary dictionary];
        resultDict[@"code"] = @(code);
        resultDict[@"blackBox"] = blackBox;
        resultDict[@"fpVersion"] = fpVersion;
        resultDict[@"anonymousId"] = anonymousId;
        resultDict[@"sealedResult"] = sealedResult;
        resultDict[@"deviceRiskScore"] = @(deviceRiskScore);
        resultDict[@"msg"] = message;

        resolve(resultDict);
    });
}

RCT_EXPORT_METHOD(sign:(NSString*)path
                 resolver:(RCTPromiseResolveBlock)resolve
                 rejecter:(RCTPromiseRejectBlock)reject)
{
  TDMobRiskManager_t *manager = [TDMobRiskManager sharedManager];
  
  TDAPISignResult signResult = manager->sign(path);

  // 获取签名并使用
  NSString* signString = signResult.sign ? [NSString stringWithUTF8String:signResult.sign] : @"";
  // 获取状态码
  int code = signResult.code;

  // 获取错误信息
  NSString* errMsgString = signResult.msg ? [NSString stringWithUTF8String:signResult.msg] : @"";
    
  // 创建结果字典
  NSMutableDictionary *resultDict = [NSMutableDictionary dictionary];
  
  // 添加所有字段
  resultDict[@"code"] = @(code);
  resultDict[@"sign"] = signString;
  resultDict[@"msg"] = errMsgString;
  
  resolve(resultDict);
}

- (UIWindow *)getKeyWindow
{
    if (@available(iOS 13.0, *))
        {
        for (UIWindowScene* windowScene in [UIApplication sharedApplication].connectedScenes) {
            if (windowScene.activationState == UISceneActivationStateForegroundActive)
                {
                for (UIWindow *window in windowScene.windows)
                    {
                    if (window.isKeyWindow)
                        {
                        return window;
                        }
                    }
                }
        }
        }
    else
        {
        return [UIApplication sharedApplication].keyWindow;
        }
    return nil;
}

RCT_REMAP_METHOD(showCaptcha,
                 showCaptchaResolver:(RCTPromiseResolveBlock)resolve
                 rejecter:(RCTPromiseRejectBlock)reject)
{
  TDMobRiskManager_t *manager = [TDMobRiskManager sharedManager];
  
  dispatch_async(dispatch_get_main_queue(), ^{
    UIWindow *keyWindow = [self getKeyWindow];
    manager->showCaptcha(keyWindow,^(TDShowCaptchaResultStruct resultStruct) {
      NSMutableDictionary *resultDictionary = [NSMutableDictionary dictionary];
      switch (resultStruct.resultType) {
        case TDShowCaptchaResultTypeSuccess:
          resultDictionary[@"function"] = @"onSuccess";
          resultDictionary[@"token"] = @(resultStruct.validateToken);
          break;
        case TDShowCaptchaResultTypeFailed:
          resultDictionary[@"function"] = @"onFailed";
          resultDictionary[@"errorCode"] = @(resultStruct.errorCode);
          resultDictionary[@"errorMsg"] = @(resultStruct.errorMsg);
          break;
        case TDShowCaptchaResultTypeReady:
          resultDictionary[@"function"] = @"onReady";
          break;
        default:
          break;
      }
      resolve(resultDictionary);
    });
  });
}



                  


@end


