import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import org.gradle.api.tasks.testing.logging.TestLogEvent.*

plugins {
  java
  application
  id("com.gradleup.shadow") version "9.4.1"
  id("com.github.node-gradle.node") version "7.1.0"
}

node {
  version.set("24.15.0") // версия Node.js
  npmVersion.set("11.12.1") // версия npm
  download.set(true) // автоматически скачать Node.js
  workDir.set(file("${project.projectDir}/.gradle/nodejs"))
  npmWorkDir.set(file("${project.projectDir}/.gradle/npm"))
  nodeProjectDir.set(file("${project.projectDir}/frontend")) // папка с Vue-проектом
}

group = "com.example"
version = "1.0.0-SNAPSHOT"

repositories {
  mavenCentral()
}

val vertxVersion = "5.0.11"

val mainVerticleName = "su.xserver.iikocon.MainVerticle"
val launcherClassName = "io.vertx.launcher.application.VertxApplication"

application {
  mainClass.set(launcherClassName)
}

dependencies {
  implementation(platform("io.vertx:vertx-stack-depchain:$vertxVersion"))
  implementation("io.vertx:vertx-launcher-application")
  implementation("io.vertx:vertx-web-client")
  implementation("io.vertx:vertx-config")
  implementation("io.vertx:vertx-sql-client-templates")
  implementation("io.vertx:vertx-health-check")
  implementation("io.vertx:vertx-web")
  implementation("io.vertx:vertx-mysql-client")
  implementation("io.vertx:vertx-redis-client")
  implementation("io.vertx:vertx-web-sstore-redis")
  implementation("io.vertx:vertx-mail-client")

  implementation("com.fasterxml.jackson.core:jackson-databind")

  // Source: https://mvnrepository.com/artifact/org.mindrot/jbcrypt
  implementation("org.mindrot:jbcrypt:0.4")
  // Source: https://mvnrepository.com/artifact/org.slf4j/slf4j-api
  implementation("org.slf4j:slf4j-api:2.0.17")
  // Source: https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-slf4j2-impl
  implementation("org.apache.logging.log4j:log4j-slf4j2-impl:2.25.4")
  // Source: https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core
  implementation("org.apache.logging.log4j:log4j-core:2.25.4")
  // Source: https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api
  implementation("org.apache.logging.log4j:log4j-api:2.25.4")

  implementation("io.vertx:vertx-jdbc-client")

  // Source: https://mvnrepository.com/artifact/com.clickhouse/clickhouse-jdbc
  implementation("com.clickhouse:clickhouse-jdbc:0.9.8")
  // Source: https://mvnrepository.com/artifact/com.mysql/mysql-connector-j
  implementation("com.mysql:mysql-connector-j:9.7.0")
  // Source: https://mvnrepository.com/artifact/org.postgresql/postgresql
  implementation("org.postgresql:postgresql:42.7.11")

}

java {
  sourceCompatibility = JavaVersion.VERSION_21
  targetCompatibility = JavaVersion.VERSION_21
}

tasks.withType<ShadowJar> {
  archiveClassifier.set("fat")
  manifest {
    attributes(mapOf("Main-Verticle" to mainVerticleName))
  }
  mergeServiceFiles()
}

tasks.withType<Test> {
  useJUnitPlatform()
  testLogging {
    events = setOf(PASSED, SKIPPED, FAILED)
  }
}

tasks.withType<JavaExec> {
  args = listOf(mainVerticleName)
}

val buildFrontend by tasks.registering {
  group = "build"
  description = "Build Vue frontend"
  dependsOn("npm_install")   // установка зависимостей
  dependsOn("npm_run_build") // сборка (должен быть скрипт "build" в package.json)
}

tasks.processResources {
  dependsOn(buildFrontend)
}

tasks.register("collectAllDependencies") {
  group = "project"
  description = "Сбор всех зависимостей для офлайн работы"

  doLast {
    val outDir = File("${rootDir}/libs")
    outDir.mkdirs()

    val allArtifacts = configurations
      .filter { it.isCanBeResolved }
      .flatMap { config ->
        config.resolvedConfiguration.lenientConfiguration.allModuleDependencies.flatMap { dep ->
          dep.allModuleArtifacts
        }
      }
      // ❗ Исключаем артефакты локальных проектов (например, :library)
      .filterNot { artifact ->
        artifact.id.componentIdentifier.displayName.startsWith("project ")
      }
      .distinctBy { it.file.name }

    allArtifacts.forEach { artifact ->
      val outFile = outDir.resolve(artifact.file.name)
      if (!outFile.exists() && artifact.file.exists()) {
        println("⬇️ Copying ${artifact.moduleVersion.id.group}:${artifact.name}:${artifact.moduleVersion.id.version} ...")
        artifact.file.inputStream().use { input ->
          outFile.outputStream().use { output ->
            input.copyTo(output)
          }
        }
      }
    }
    println("✅ All dependencies are collected in \"libs\"")
  }
}

