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

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

static NSString *TDSeString(const char *value) {
  return value ? ([NSString stringWithUTF8String:value] ?: @"") : @"";
}

static NSDictionary *TDSeDeviceInfoDictionary(TDDeviceResponse response) {
  NSString *message = TDSeString(response.apiStatus.message);
  return @{
    @"blackBox": TDSeString(response.blackBox),
    @"fpVersion": TDSeString(response.fpVersion),
    @"anonymousId": TDSeString(response.anonymousId),
    @"deviceRiskScore": @(response.deviceRiskScore),
    @"sealedResult": TDSeString(response.sealedResult),
    @"apiStatus": @{ @"code": @(response.apiStatus.code), @"message": message },
    @"code": @(response.apiStatus.code),
    @"msg": message,
  };
}

@implementation TrustDeviceSe

RCT_EXPORT_MODULE();

- (NSArray<NSString *> *)supportedEvents {
  return @[@"TrustDeviceSeCaptcha"];
}

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];
  if ([options[@"debug"] isKindOfClass:[NSNumber class]] && [options[@"debug"] boolValue]) {
    mutableOptions[@"allowed"] = @"allowed";
  }
  if ([options[@"location"] isKindOfClass:[NSNumber class]] && ![options[@"location"] boolValue]) {
    mutableOptions[@"noLocation"] = @"noLocation";
  }
  if ([options[@"IDFA"] isKindOfClass:[NSNumber class]] && ![options[@"IDFA"] boolValue]) {
    mutableOptions[@"noIDFA"] = @"noIDFA";
  }
  if ([options[@"deviceName"] isKindOfClass:[NSNumber class]] && ![options[@"deviceName"] boolValue]) {
    mutableOptions[@"noDeviceName"] = @"noDeviceName";
  }
  NSString *dataCenter = options[@"dataCenter"];
  if ([dataCenter isKindOfClass:[NSString class]] && dataCenter.length > 0) {
    mutableOptions[@"country"] = dataCenter;
  }

  TDDeviceManager_t *manager = [TDDeviceManager sharedManager];
  manager->initWithOptions([mutableOptions copy]);
}

RCT_REMAP_METHOD(getDeviceInfo,
                 getDeviceInfoResolver:(RCTPromiseResolveBlock)resolve
                 rejecter:(RCTPromiseRejectBlock)reject)
{
  [self resolveDeviceInfo:resolve rejecter:reject];
}

RCT_REMAP_METHOD(getDeviceInfoAsync,
                 getDeviceInfoAsyncResolver:(RCTPromiseResolveBlock)resolve
                 rejecter:(RCTPromiseRejectBlock)reject)
{
  [self resolveDeviceInfo:resolve rejecter:reject];
}

- (void)resolveDeviceInfo:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject {
  TDDeviceManager_t *manager = [TDDeviceManager sharedManager];
  if (manager == NULL || manager->getDeviceInfo == NULL) {
    reject(@"device_info_unavailable", @"getDeviceInfo is unavailable", nil);
    return;
  }
  manager->getDeviceInfo(^(TDDeviceResponse response) {
    resolve(TDSeDeviceInfoDictionary(response));
  });
}

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];
  if (manager == NULL || manager->showCaptcha == NULL) {
    reject(@"captcha_unavailable", @"showCaptcha is unavailable", nil);
    return;
  }
  dispatch_async(dispatch_get_main_queue(), ^{
    UIWindow *keyWindow = [self getKeyWindow];
    if (keyWindow == nil) {
      reject(@"captcha_no_window", @"No active application window", nil);
      return;
    }
    manager->showCaptcha(keyWindow,^(TDShowCaptchaResultStruct resultStruct) {
      NSDictionary *resultDictionary;
      switch (resultStruct.resultType) {
        case TDShowCaptchaResultTypeSuccess:
          resultDictionary = @{ @"function": @"onSuccess", @"token": TDSeString(resultStruct.validateToken) };
          break;
        case TDShowCaptchaResultTypeFailed:
          resultDictionary = @{ @"function": @"onFailed", @"errorCode": @(resultStruct.errorCode),
                                @"errorMsg": TDSeString(resultStruct.errorMsg) };
          break;
        case TDShowCaptchaResultTypeReady: {
          dispatch_async(dispatch_get_main_queue(), ^{
            [self sendEventWithName:@"TrustDeviceSeCaptcha" body:@{ @"function": @"onReady" }];
          });
          return;
        }
        default:
          return;
      }
      resolve(resultDictionary);
    });
  });
}

RCT_REMAP_METHOD(showLiveness,
                 showLivenessWithOptions:(NSDictionary *)options
                 resolver:(RCTPromiseResolveBlock)resolve
                 rejecter:(RCTPromiseRejectBlock)reject)
{
  TDMobRiskManager_t *manager = [TDMobRiskManager sharedManager];
  if (manager == NULL || manager->showLivenessWithShowStyle == NULL) {
    reject(@"liveness_unavailable", @"showLiveness is unavailable", nil);
    return;
  }
  dispatch_async(dispatch_get_main_queue(), ^{
    UIViewController *controller = [self getKeyWindow].rootViewController;
    while (controller.presentedViewController != nil) {
      controller = controller.presentedViewController;
    }
    if (controller == nil) {
      reject(@"liveness_no_controller", @"No active view controller", nil);
      return;
    }
    NSString *license = [options[@"license"] isKindOfClass:[NSString class]] ? options[@"license"] : nil;
    TDLivenessShowStyle style = [options[@"showStyle"] isEqual:@"push"]
      ? TDLivenessShowStylePush : TDLivenessShowStylePresent;
    manager->showLivenessWithShowStyle(controller, license, style,
      ^(NSDictionary *success) {
        NSMutableDictionary *result = [success mutableCopy] ?: [NSMutableDictionary dictionary];
        result[@"function"] = @"onSuccess";
        resolve(result);
      },
      ^(NSDictionary *failure) {
        NSMutableDictionary *result = [failure mutableCopy] ?: [NSMutableDictionary dictionary];
        result[@"function"] = @"onFailed";
        resolve(result);
      });
  });
}


                  


@end


