import java.util.Properties
import java.io.FileInputStream
import groovy.json.JsonSlurper

plugins {
    id("com.android.application")
    id("org.jetbrains.kotlin.android")
    id("com.google.gms.google-services")
    id("dev.flutter.flutter-gradle-plugin")
}

flutter {
    // path tới thư mục gốc Flutter project
    source = "../.."
}

val keystoreProps = Properties().apply {
    val f = File(projectDir, "keystores/key.properties")
    if (f.exists()) load(FileInputStream(f))
}

// --- Helper đọc env.json theo flavor ---
fun readEnvJson(flavor: String): Map<String, Any> {
    val envFile = file("src/$flavor/assets/config/env.json")
    return if (envFile.exists()) {
        val json = JsonSlurper().parseText(envFile.readText()) as Map<String, Any>
        json
    } else {
        mapOf(
            "baseUrl" to "https://api.sandbox.mypoint.com.vn/8854/gup2start/rest",
            "t3Token" to "android-app-src-build-gradle-kts",
            "enableLogging" to true
        )
    }
}

android {
    namespace = "com.icom.mypoint"
    compileSdk = 36

    defaultConfig {
        applicationId = "com.icom.mypoint"
        minSdk = flutter.minSdkVersion
        targetSdk = flutter.targetSdkVersion
        versionCode = flutter.versionCode
        versionName = flutter.versionName
        manifestPlaceholders.putAll(
            mapOf(
                "branch_key_live" to "key_live_jzBfMtoh49vCAG0GzGrzHdoiFFh7oyKw",
                "branch_key_test" to "key_test_mqEkGCao05wFFO4UwPw6GfglyzeZfuIV",
                "branch_uri_scheme" to "mypointapp",
                "branch_app_domain" to "mypoint.app.link",
                "branch_app_domain_test" to "mypoint.test-app.link",
                "branch_alt_domain" to "mypoint-alternate.app.link",
                "branch_alt_domain_test" to "mypoint-alternate.test-app.link",
                "branch_test_mode" to "false"
            )
        )
    }

    signingConfigs {
        create("release") {
            if (keystoreProps.getProperty("storeFile") != null) {
                storeFile = file(keystoreProps.getProperty("storeFile"))
                storePassword = keystoreProps.getProperty("storePassword")
                keyAlias = keystoreProps.getProperty("keyAlias")
                keyPassword = keystoreProps.getProperty("keyPassword")
            } else {
                logger.warn("storeFile missing in key.properties; release build will be unsigned.")
            }
        }
    }

    buildTypes {
        getByName("debug") {
            isMinifyEnabled = false
        }
        getByName("release") {
            signingConfig = signingConfigs.findByName("release")
            isMinifyEnabled = true
            isShrinkResources = true
            proguardFiles(
                getDefaultProguardFile("proguard-android-optimize.txt"),
                "proguard-rules.pro"
            )
        }
    }

    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_17
        targetCompatibility = JavaVersion.VERSION_17
        isCoreLibraryDesugaringEnabled = true
    }
    kotlinOptions {
        jvmTarget = "17"
    }
    buildFeatures {
        buildConfig = true
    }
    lint {
        disable += setOf("NullSafeMutableLiveData")
        abortOnError = false
    }

    // --- Flavors giữ nguyên ENV của bạn ---
    flavorDimensions += "environment"
    productFlavors {
        create("dev") {
            dimension = "environment"
            val env = readEnvJson("dev")
            buildConfigField("String", "BASE_URL", "\"${env["baseUrl"]}\"")
            buildConfigField("String", "LIB_TOKEN", "\"${env["t3Token"]}\"")
            buildConfigField("boolean", "ENABLE_LOGGING", "${env["enableLogging"]}")
            applicationIdSuffix = ".dev"
            versionNameSuffix = "-dev"
            manifestPlaceholders["branch_test_mode"] = "true"
        }
        create("stg") {
            dimension = "environment"
            val env = readEnvJson("stg")
            buildConfigField("String", "BASE_URL", "\"${env["baseUrl"]}\"")
            buildConfigField("String", "LIB_TOKEN", "\"${env["t3Token"]}\"")
            buildConfigField("boolean", "ENABLE_LOGGING", "${env["enableLogging"]}")
            applicationIdSuffix = ".stg"
            versionNameSuffix = "-stg"
        }
        create("pro") {
            dimension = "environment"
            val env = readEnvJson("pro")
            buildConfigField("String", "BASE_URL", "\"${env["baseUrl"]}\"")
            buildConfigField("String", "LIB_TOKEN", "\"${env["t3Token"]}\"")
            buildConfigField("boolean", "ENABLE_LOGGING", "${env["enableLogging"]}")
        }
    }
}

dependencies {
    coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.4")
    implementation(platform("com.google.firebase:firebase-bom:33.3.0"))
    implementation("com.google.firebase:firebase-messaging")
}
