import java.time.Duration

buildscript {
    repositories {
        mavenCentral()
    }
}

plugins {
    id 'java'
    id 'pl.allegro.tech.build.axion-release' version '1.13.6'
    id 'io.github.gradle-nexus.publish-plugin' version '1.0.0'
}

scmVersion {
    tag {
        prefix = 'hermes-'
    }

    versionCreator 'versionWithBranch'
}

java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(21)
    }
}

nexusPublishing {
    connectTimeout = Duration.ofMinutes(getIntProperty('publishingTimeoutInMin', 10))
    clientTimeout = Duration.ofMinutes(getIntProperty('publishingTimeoutInMin', 10))
    repositories {
        sonatype {
            nexusUrl.set(uri("https://ossrh-staging-api.central.sonatype.com/service/local/"))
            snapshotRepositoryUrl.set(uri("https://central.sonatype.com/repository/maven-snapshots/"))
            stagingProfileId = '19d6feb4b1fb3' // id for group 'pl.allegro.tech.hermes'
            username = System.getenv("SONATYPE_USERNAME")
            password = System.getenv("SONATYPE_PASSWORD")
        }
    }
    transitionCheckOptions {
        maxRetries.set(getIntProperty('attemptsToCloseStagingRepository', 30))
        delayBetween.set(Duration.ofSeconds(getIntProperty('delayInSecBetweenCloseStagingRepositoryAttempts', 45)))
    }
}

allprojects {
    apply plugin: 'java'
    apply plugin: 'groovy'

    group = 'pl.allegro.tech.hermes'
    version = scmVersion.version

    project.ext.versions = [
            kafka             : '2.8.2',
            guava             : '33.1.0-jre',
            jackson           : '2.17.0',
            jersey            : '3.1.6',
            jetty             : '12.0.8',
            curator           : '5.4.0',
            dropwizard_metrics: '4.2.25',
            micrometer_metrics: '1.13.0',
            wiremock          : '3.9.0',
            spock             : '2.4-M4-groovy-4.0',
            groovy            : '4.0.21',
            avro              : '1.11.3',
            json2avro         : '0.2.14',
            // TODO: newest version requires subject alternative name in a certificate during host verification, current test cert does not have a one
            okhttp            : '3.9.1',
            undertow          : '2.3.12.Final',
            spring_web        : '6.1.6',
            failsafe          : '3.3.2',
            junit_jupiter     : '5.10.2',
            testcontainers    : '1.19.8',
            spring            : '3.2.4',
            assertj           : '3.25.3',
            allure            : '2.24.0'
    ]

    repositories {
        mavenCentral()
    }

    dependencies {
        implementation group: 'org.slf4j', name: 'slf4j-api', version: '2.0.4'
        implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.14.0'

        // Allure Spock adapter
        testImplementation(platform("io.qameta.allure:allure-bom:${versions.allure}"))
        testImplementation("io.qameta.allure:allure-spock2")
        testImplementation("io.qameta.allure:allure-junit-platform")

        // Spock framework
        testImplementation(platform("org.spockframework:spock-bom:${versions.spock}"))
        testImplementation("org.spockframework:spock-core")

        testImplementation group: 'junit', name: 'junit', version: '4.11'
        testImplementation group: 'com.tngtech.java', name: 'junit-dataprovider', version: '1.10.0'
        testImplementation group: 'pl.pragmatists', name: 'JUnitParams', version: '1.0.2'
        testImplementation group: 'org.mockito', name: 'mockito-core', version: '5.11.0'
        testImplementation group: 'org.assertj', name: 'assertj-core', version: versions.assertj
        testImplementation group: 'org.awaitility', name: 'awaitility', version: '4.2.1'

        annotationProcessor group: 'org.springframework.boot', name: 'spring-boot-configuration-processor', version: versions.spring
    }

    // https://chronicle.software/chronicle-support-java-17/
    ext.chronicleMapJvmArgs = ["--add-exports=java.base/jdk.internal.ref=ALL-UNNAMED",
                               "--add-exports=java.base/sun.nio.ch=ALL-UNNAMED",
                               "--add-exports=jdk.unsupported/sun.misc=ALL-UNNAMED",
                               "--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED",
                               "--add-opens=jdk.compiler/com.sun.tools.javac=ALL-UNNAMED",
                               "--add-opens=java.base/java.lang=ALL-UNNAMED",
                               "--add-opens=java.base/java.lang.reflect=ALL-UNNAMED",
                               "--add-opens=java.base/java.io=ALL-UNNAMED",
                               "--add-opens=java.base/java.util=ALL-UNNAMED"]

    test {
        useJUnitPlatform()
        def args = []
        if (project.hasProperty('tests.timeout.multiplier')) {
            args = ["-Dtests.timeout.multiplier=${project.property('tests.timeout.multiplier')}"]
        }
        args += chronicleMapJvmArgs
        jvmArgs = args
    }
}


configure(subprojects - project(':integration-tests')) {
    apply plugin: 'jacoco'
    apply plugin: 'maven-publish'
    apply plugin: 'signing'

    java {
        withJavadocJar()
        withSourcesJar()
    }

    javadoc.options.addStringOption('Xdoclint:none', '-quiet')

    publishing {
        publications {
            mavenJava(MavenPublication) {
                artifactId = project.name
                from(components.java)
                pom {
                    name = project.name
                    description = 'Fast and reliable message broker built on top of Kafka.'
                    url = 'https://github.com/allegro/hermes'
                    inceptionYear = '2015'
                    licenses {
                        license {
                            name = 'The Apache Software License, Version 2.0'
                            url = 'http://www.apache.org/licenses/LICENSE-2.0.txt'
                        }
                    }
                    developers {
                        developer {
                            id = 'skyeden'
                            name = 'Skylab Eden Team'
                        }
                    }
                    scm {
                        url = 'https://github.com/allegro/hermes'
                        connection = 'scm:git@github.com:allegro/hermes.git'
                        developerConnection = 'scm:git@github.com:allegro/hermes.git'
                    }
                }
            }
        }
    }

    if (System.getenv("GPG_KEY_ID")) {
        signing {
            useInMemoryPgpKeys(
                    System.getenv("GPG_KEY_ID"),
                    System.getenv("GPG_PRIVATE_KEY"),
                    System.getenv("GPG_PRIVATE_KEY_PASSWORD")
            )
            sign publishing.publications.mavenJava
        }
    }
}

subprojects {
    configurations {
        all*.exclude group: "org.slf4j", module: "slf4j-log4j12"
        all*.exclude group: "log4j", module: "log4j"
        all*.resolutionStrategy*.force "com.google.guava:guava:${versions.guava}"
        all*.resolutionStrategy*.force "com.fasterxml.jackson.core:jackson-databind:${versions.jackson}"
        all*.resolutionStrategy*.force "com.fasterxml.jackson.core:jackson-annotations:${versions.jackson}"
        all*.resolutionStrategy*.force "com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:${versions.jackson}"
    }

    tasks.withType(JavaCompile) {
        options.compilerArgs << "-Xlint:unchecked,deprecation"
    }

    test {
        reports {
            html.required = false
            junitXml.required = true
            junitXml.outputLocation = file("$buildDir/test-results/$name")
        }

        testLogging {
            exceptionFormat = 'full'
            events 'passed', 'skipped', 'failed'
        }
    }
}

def getIntProperty(String name, int defaultValue) {
    Integer.valueOf(project.findProperty(name) ?: defaultValue)
}
