plugins {
    alias libs.plugins.release.automation.plugin
    alias libs.plugins.release.plugin
}

def versionProps = new Properties()
file("version.properties").withInputStream { versionProps.load(it) }

tasks.register('printVersion') {
    doFirst {
        println('Domain Lifecycles Version: ' + versionProps.getProperty("version"))
    }
}

release {
    failOnCommitNeeded = true
    failOnPublishNeeded = true
    failOnSnapshotDependencies = false
    failOnUnversionedFiles = true
    failOnUpdateNeeded = true
    revertOnFail = true
    preCommitText = ''
    preTagCommitMessage = '[Gradle Release Plugin] - pre tag commit: '
    tagCommitMessage = '[Gradle Release Plugin] - creating tag: '
    newVersionCommitMessage = '[Gradle Release Plugin] - new version commit: '
    tagTemplate = '${version}'
    versionPropertyFile = 'version.properties'
    versionProperties = ['version']
    snapshotSuffix = '-SNAPSHOT'
    scmAdapters = [
            net.researchgate.release.GitAdapter
    ]

    git {
        requireBranch.set('main')
        pushToRemote.set('origin')
        commitVersionFileOnly.set(true)
        signTag.set(false)
    }
}

ext {
    dlcGroup = 'io.domainlifecycles'
    dlcVersion = versionProps.getProperty("version")
}

allprojects {

    plugins.withType(JavaPlugin).configureEach {
        repositories {
            mavenCentral()
        }
        dependencies {
            testImplementation libs.junit.api
            testRuntimeOnly libs.junit.engine
        }
        test {
            useJUnitPlatform()
            testLogging {
                for (def level : LogLevel.values()) {
                    def testLogging = get(level)
                    testLogging.exceptionFormat = 'full'
                    testLogging.events = ["FAILED", "STANDARD_OUT", "STANDARD_ERROR"]
                }
            }
            maxParallelForks(1)
        }
        java {
            toolchain {
                languageVersion = JavaLanguageVersion.of(17)
            }
        }
        tasks.withType(Jar) {
            includeEmptyDirs = false
            enabled = true
        }
        tasks.withType(JavaCompile) {
            options.encoding = "UTF-8"
        }
        javadoc {
            title = '<h1>DomainLifecycles</h1>'
            options.bottom = '<i>provided by esentri.</i>'
            options.encoding = 'UTF-8'
            options.docEncoding = 'UTF-8'
            options.charSet = 'UTF-8'
            //options.links("https://docs.oracle.com/en/java/javase/${buildJavaVersion}/docs/api/")
            options.addBooleanOption 'html5', true
            options.tags(
                    'apiNote:a:API Note:',
                    'implSpec:a:Implementation Requirements:',
                    'implNote:a:Implementation Note:'
            )

        }
    }

    plugins.withId('checkstyle') {
        checkstyle {
            toolVersion = '10.12.4'
            configFile = rootProject.file('./checkstyle/checkstyle.xml')
            ignoreFailures = true
            showViolations = true

            checkstyleMain.source = "src/main/java"
        }
    }

    plugins.withId('dev.yumi.gradle.licenser') {
        checkLicenseMain.enabled = true
        checkLicenseTest.enabled = false
        license {
            // Add a license header rule, at least one must be present.
            rule(file("./copyright/HEADER"))
            // Apply license header ONLY to Java files
            exclude("**/tests/**/*.java")
            exclude("**/test/**/*.java")
            exclude("**/sampleshop/**/*.java")
        }
    }

    plugins.withId('maven-publish') {

        afterEvaluate {
            publishing {
                publications {
                    mavenJava(MavenPublication) {
                        groupId = dlcGroup
                        version = dlcVersion

                        from components.java

                        pom {
                            name = 'Domain Lifecycles'
                            description = 'Simplify Domain-Driven Design in Java'
                            url = 'https://www.domainlifecycles.io'

                            licenses {
                                license {
                                    name = 'The Apache License, Version 2.0'
                                    url = 'http://www.apache.org/licenses/LICENSE-2.0.txt'
                                }
                            }
                            developers {
                                developer {
                                    id = 'mherb'
                                    name = 'Mario Herb'
                                    email = 'mario.herb@esentri.com'
                                    organization = 'esentri AG'
                                    organizationUrl = 'https://www.esentri.com'
                                }
                                developer {
                                    id = 'dgaller'
                                    name = 'Dominik Galler'
                                    email = 'dominik.galler@esentri.com'
                                    organization = 'esentri AG'
                                    organizationUrl = 'https://www.esentri.com'
                                }
                            }
                            scm {
                                connection = 'scm:git@github.com:esentri/domainlifecycles.git'
                                url = 'https://github.com/esentri/domainlifecycles/'
                            }
                        }
                    }
                }

                repositories {
                    maven {
                        url = '../build/staging-deploy'
                    }
                }
            }
        }
    }
}

// ----------------------------------------------------------
//  RELEASE TO MAVEN CENTRAL
// ----------------------------------------------------------

jreleaser {
    project {
        java.groupId = 'io'
        version = versionProps.getProperty("version")
        description = 'A Java framework for developing applications using Domain-Driven Design.'
        copyright = 'The Apache License, Version 2.0'
    }
    signing {
        active = 'ALWAYS'
        armored = true
    }
    deploy {
        maven {
            mavenCentral {
                sonatype {
                    active = 'ALWAYS'
                    url = 'https://central.sonatype.com/api/v1/publisher'
                    stagingRepository('build/staging-deploy')
                }
            }
        }
    }
}

// ----------------------------------------------------------
//  AUTOMATE SETTING PROJECT VERSION IN readme.md
// ----------------------------------------------------------


tasks.register("updateReadme") {
    doLast {
        def projectVersion= versionProps.getProperty("version")
        def readmeFile = file("readme.md")
        def content = readmeFile.text

        // Gradle in Readme
        def updatedContent = content.replaceAll(
            /io\.domainlifecycles:spring-boot-3-jooq-complete:\d+\.\d+\.\d+/,
            "io.domainlifecycles:spring-boot-3-jooq-complete:${projectVersion}"
        ).replaceAll(
            /(<groupId>io\.domainlifecycles<\/groupId>\s*<artifactId>spring-boot-3-jooq-complete<\/artifactId>\s*<version>)(\d+\.\d+\.\d+)(<\/version>)/,
            "\$1${projectVersion}\$3"
        )

        readmeFile.text = updatedContent
        println("Updated README.md with version $projectVersion")
    }
}

// Sets the version in readme.md when build is triggered!
tasks.named("build") {
    dependsOn("updateReadme")
}

// ----------------------------------------------------------
//  GRADLE.WRAPPER
// ----------------------------------------------------------

wrapper {
    gradleVersion = '8.10.1'
    distributionType = 'ALL'
}

