import java.util.Properties
import java.io.FileInputStream
import java.io.FileOutputStream

plugins {
    id("com.android.application")
    id("kotlin-android")
    // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
    id("dev.flutter.flutter-gradle-plugin")
}

// ============================================
// Auto-increment version code on each build
// ============================================
val versionPropertiesFile = rootProject.file("app/version.properties")
val versionProperties = Properties()

fun calculateNextVersionCode(): Int {
    if (versionPropertiesFile.exists()) {
        versionProperties.load(FileInputStream(versionPropertiesFile))
    }
    val currentCode = versionProperties.getProperty("VERSION_CODE", "0").toInt()
    val newCode = currentCode + 1
    versionProperties.setProperty("VERSION_CODE", newCode.toString())
    versionProperties.store(FileOutputStream(versionPropertiesFile), "Auto-generated version code - DO NOT EDIT MANUALLY")
    return newCode
}

val autoVersionCode = calculateNextVersionCode()

// Version name: major.minor.patch (from pubspec.yaml) + build number
// Example: 1.0.0.42
fun getAutoVersionName(): String {
    val flutterVersionName = flutter.versionName
    return "$flutterVersionName.$autoVersionCode"
}

android {
    namespace = "com.iagent.it0_app"
    compileSdk = flutter.compileSdkVersion
    ndkVersion = flutter.ndkVersion

    compileOptions {
        isCoreLibraryDesugaringEnabled = true
        sourceCompatibility = JavaVersion.VERSION_17
        targetCompatibility = JavaVersion.VERSION_17
    }

    kotlinOptions {
        jvmTarget = JavaVersion.VERSION_17.toString()
    }

    defaultConfig {
        applicationId = "com.iagent.it0_app"
        minSdk = flutter.minSdkVersion
        targetSdk = flutter.targetSdkVersion
        versionCode = autoVersionCode
        versionName = getAutoVersionName()
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig = signingConfigs.getByName("debug")
        }
    }
}

dependencies {
    coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.4")
}

flutter {
    source = "../.."
}
