#ifndef RCT_NEW_ARCH_ENABLED

#import <React/RCTBridgeModule.h>

#if __has_include(<CheckoutReactNativeComponents/CheckoutReactNativeComponents-Swift.h>)
  #import <CheckoutReactNativeComponents/CheckoutReactNativeComponents-Swift.h>
#else
  #import <CheckoutReactNativeComponents-Swift.h>
#endif

@interface CheckoutModule : NSObject <RCTBridgeModule>
@end

@implementation CheckoutModule

RCT_EXPORT_MODULE(CheckoutModule)

+ (BOOL)requiresMainQueueSetup {
    return NO;
}

RCT_EXPORT_METHOD(initialize:(NSDictionary *)args
                  resolver:(RCTPromiseResolveBlock)resolve
                  rejecter:(RCTPromiseRejectBlock)reject) {
    CheckoutModuleHandler *handler = [CheckoutModuleHandler sharedInstance];
    [handler initializeWithArgs:args completion:^(NSError * _Nullable error) {
        if (error) {
            NSString *code = [NSString stringWithFormat:@"%ld", (long)error.code];
            reject(code, error.localizedDescription, error);
        } else {
            resolve(@(YES));
        }
    }];
}

RCT_EXPORT_METHOD(clear:(RCTPromiseResolveBlock)resolve
                  rejecter:(RCTPromiseRejectBlock)reject) {
    CheckoutModuleHandler *handler = [CheckoutModuleHandler sharedInstance];
    BOOL success = [handler clear];
    if (success) {
        resolve(@(YES));
    } else {
        NSError *error = [CheckoutErrorBridge errorFor:CheckoutErrorClearFailed];
        NSString *code = [NSString stringWithFormat:@"%ld", (long)error.code];
        reject(code, error.localizedDescription, error);
    }
}

RCT_EXPORT_METHOD(resolveSubmit:(NSString *)callbackId
                  arguments:(NSDictionary *)args
                  resolver:(RCTPromiseResolveBlock)resolve
                  rejecter:(RCTPromiseRejectBlock)reject) {
    CheckoutModuleHandler *handler = [CheckoutModuleHandler sharedInstance];
    [handler resolveSubmitWithCallbackId:callbackId args:args completion:^(NSError * _Nullable error) {
      if (error) {
          NSString *code = [NSString stringWithFormat:@"%ld", (long)error.code];
          reject(code, error.localizedDescription, error);
      } else {
          resolve(@(YES));
      }
    }];
}

RCT_EXPORT_METHOD(resolveTokenized:(NSString *)callbackId
                  result:(BOOL)success
                  error:(NSString *)error
                  resolver:(RCTPromiseResolveBlock)resolve
                  rejecter:(RCTPromiseRejectBlock)reject) {
    CheckoutModuleHandler *handler = [CheckoutModuleHandler sharedInstance];
    [handler resolveTokenizedWithCallbackId:callbackId success:success error:error completion:^(NSError * _Nullable error) {
      if (error) {
          NSString *code = [NSString stringWithFormat:@"%ld", (long)error.code];
          reject(code, error.localizedDescription, error);
      } else {
          resolve(@(YES));
      }
  }];
}
@end

#endif
