plugins {
    id 'epilink.js-conventions'
    id "java" // For easier jar creation (not strictly necessary but would require more config without it)
}

String backEndUrl() {
    if (project.hasProperty("backendUrl")) {
        return project.property("backendUrl")
    } else if (project.hasProperty("withFrontend")) {
        return "/"
    } else {
        return null
    }
}

task bundleWeb(type: NpmTask) {
    dependsOn npmInstall

    inputs.file('index.html')
    inputs.file('package-lock.json')
    inputs.files(fileTree('public'))
    inputs.files(fileTree('src'))
    inputs.files(fileTree('assets'))
    inputs.file('package.json')
    inputs.file('vite.config.js')
    inputs.property("backendUrl", backEndUrl())

    outputs.dir(layout.buildDirectory.dir("web"))

    args = ['run', 'prod']

    String backendUrl = backEndUrl()
    if (backendUrl != null)
        environment = ['BACKEND_URL': backendUrl]
}

task serveWeb(type: NpmTask) {
    dependsOn npmInstall
    args = ['run', 'dev']

    String backendUrl = backEndUrl()
    if (backendUrl != null)
        environment = ['BACKEND_URL': backendUrl]
}

task frontendJar(type: Jar) {
    archiveBaseName = 'epilink-frontend'
    from(bundleWeb) {
        into "frontend"
    }
    from fileTree("bundled/")
}

configurations {
    frontendJarCfg {
        canBeConsumed = true
        canBeResolved = false
    }
}

artifacts {
    frontendJarCfg(frontendJar)
}
