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
    }

    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
    }

    // --- 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"
        }
        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")
}
