buildscript {
  ext.getExtOrDefault = {name ->
    return rootProject.ext.has(name) ? rootProject.ext.get(name) : project.properties['HyperswitchSdkReactNative_' + name]
  }

  repositories {
    google()
    mavenCentral()
  }

  dependencies {
    classpath "com.android.tools.build:gradle:8.7.2"
  }
}

apply plugin: "com.android.library"
apply plugin: "kotlin-android"
apply plugin: "kotlin-parcelize"

def getExtOrIntegerDefault(name) {
  return rootProject.ext.has(name) ? rootProject.ext.get(name) : (project.properties["HyperswitchSdkReactNative_" + name]).toInteger()
}

def isNewArchitectureEnabled() {
  // To opt-in for the New Architecture, you can either:
  // - Set `newArchEnabled` to true inside the `gradle.properties` file
  // - Invoke gradle with `-newArchEnabled=true`
  // - Set an environment variable `ORG_GRADLE_PROJECT_newArchEnabled=true`
  return project.hasProperty("newArchEnabled") && project.newArchEnabled == "true"
}

if (isNewArchitectureEnabled()) {
  apply plugin: "com.facebook.react"
}

def safeExtGet(prop, fallback) {
  rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback
}

def resolveReactNativeDirectory() {
  def reactNativeLocation = safeExtGet("REACT_NATIVE_NODE_MODULES_DIR", null)
  if (reactNativeLocation != null) {
    return file(reactNativeLocation)
  }

  // Fallback to node resolver for custom directory structures like monorepos.
  def reactNativePackage = file(
    providers.exec {
      workingDir(rootDir)
      commandLine("node", "--print", "require.resolve('react-native/package.json')")
    }.standardOutput.asText.get().trim()
  )
  if (reactNativePackage.exists()) {
    return reactNativePackage.parentFile
  }

  throw new GradleException("[@juspay-tech/react-native-hyperswitch] Unable to resolve react-native location in node_modules. Your app should define `REACT_NATIVE_NODE_MODULES_DIR` extension property in `app/build.gradle` with a path to react-native in node_modules.")
}

def reactNativeRootDir = resolveReactNativeDirectory()
def reactNativeProperties = new Properties()
file("$reactNativeRootDir/ReactAndroid/gradle.properties").withInputStream { reactNativeProperties.load(it) }

def REACT_NATIVE_VERSION = reactNativeProperties.getProperty("VERSION_NAME")
def REACT_NATIVE_MINOR_VERSION = REACT_NATIVE_VERSION.startsWith("0.0.0-") ? 1000 : REACT_NATIVE_VERSION.split("\\.")[1].toInteger()
def REACT_NATIVE_VERSION_NAME = "rn${REACT_NATIVE_MINOR_VERSION}"

def packageJsonFile = file("../package.json")
if (!packageJsonFile.exists()) {
  throw new GradleException(
    "[@juspay-tech/react-native-hyperswitch] package.json not found at ${packageJsonFile.absolutePath}; unable to determine the SDK version"
  )
}
def packageJson
try {
  packageJson = new groovy.json.JsonSlurper().parseText(packageJsonFile.text)
} catch (Exception e) {
  throw new GradleException(
    "[@juspay-tech/react-native-hyperswitch] Failed to parse ${packageJsonFile.absolutePath}: ${e.message}", e
  )
}
if (!packageJson.version) {
  throw new GradleException(
    "[@juspay-tech/react-native-hyperswitch] 'version' not found in ${packageJsonFile.absolutePath}"
  )
}
version = packageJson.version

//print("${REACT_NATIVE_VERSION_NAME}")
android {
  namespace "com.hyperswitchsdkreactnative"

  compileSdkVersion getExtOrIntegerDefault("compileSdkVersion")

  defaultConfig {
    minSdkVersion getExtOrIntegerDefault("minSdkVersion")
    targetSdkVersion getExtOrIntegerDefault("targetSdkVersion")
    versionCode 1
    versionName "1.0"
    buildConfigField "String", "VERSION_NAME", "\"${version}\""
    buildConfigField "boolean", "IS_HERMES_ENABLED", hermesEnabled
    buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", newArchEnabled
    // manifestPlaceholders = [
    //   hermesEnabled: hermesEnabled,
    //   newArchEnabled : newArchEnabled
    // ]
  }
  buildFeatures {
    buildConfig true
  }

  buildTypes {
    release {
      minifyEnabled false
      proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
    debug {
      debuggable true
    }
  }

  lintOptions {
    disable "GradleCompatible"
    abortOnError false
  }

  compileOptions {
    sourceCompatibility JavaVersion.VERSION_17
    targetCompatibility JavaVersion.VERSION_17
  }

  kotlinOptions {
    jvmTarget = '17'
  }

  sourceSets.main {
    manifest.srcFile "src/main/AndroidManifest.xml"
    assets.srcDirs = REACT_NATIVE_MINOR_VERSION >= 82
      ? ["src/main/assets"]
      : ["src/rn79/assets"]
    java {
      srcDirs += [
        "generated/java",
        "generated/jni",
        "build/generated/source/packagelist"
      ]

      if (!isNewArchitectureEnabled()) {
        srcDirs += [
          "src/legacy/java",
        ]
      }

      if (REACT_NATIVE_MINOR_VERSION >= 81) {
        srcDirs += [
          "src/rn81/java",
        ]
      } else {
        srcDirs += [
          "src/rn79/java",
        ]
      }
    }
  }

  packagingOptions {
    pickFirst '**/libc++_shared.so'
    pickFirst '**/libfbjni.so'
    pickFirst '**/libreactnativejni.so'
  }
}
apply from: "./hyperswitch_autolinking.gradle"
applyHyperswitchAutolinking(project)

dependencies {
  implementation "com.facebook.react:react-android"
  implementation "com.google.android.gms:play-services-wallet:19.4.0"
  implementation 'androidx.activity:activity-ktx:1.10.1'
  implementation 'org.greenrobot:eventbus:3.1.0'
//  implementation "io.hyperswitch:hyperswitch-sdk-android-airborne:1.0.0"
  implementation "io.hyperswitch:hyperswitch-sdk-android-common:1.0.1"
  implementation "io.hyperswitch:hyperswitch-sdk-android-logger:1.0.7"
  implementation 'io.hyperswitch:hyperswitch-sdk-android-webview-utils:1.0.6'
}
