@Suppress("SpellCheckingInspection")
plugins {
    alias(libs.plugins.kotlin.multiplatform)
    alias(libs.plugins.undercouch.download)
    alias(libs.plugins.openapi.generator)
}

repositories {
    mavenCentral()
}

kotlin {
    jvm()

    sourceSets {
        commonMain.dependencies {
            api(libs.okhttp)  // Used by the OpenAPI generated code
            implementation(libs.moshi.kotlin)  // Used by the OpenAPI generated code
        }
    }
}


// Generate source code classes corresponding to Eve's ESI API via Swagger
// https://github.com/OpenAPITools/openapi-generator/tree/master/modules/openapi-generator-gradle-plugin
val esiSwaggerUrl = project.property("esi.swagger.url") as String
val esiSwaggerFile = "$rootDir/${project.property("esi.swagger.file")}"
val esiSwaggerApiOutputPath: String = openApiGenerate.outputDir.get()  // Use whatever is the default location
val esiSwaggerApiSourcePath = "${esiSwaggerApiOutputPath}/src/main"

// Generate the Kotlin ESI code
val generateEsiApi by tasks.registering(org.openapitools.generator.gradle.plugin.tasks.GenerateTask::class) {
    group = "eve"
    generatorName.set("kotlin")
    inputSpec.set(esiSwaggerFile)
    outputDir.set(esiSwaggerApiOutputPath)
    packageName.set("eve.esi")
    generateApiTests.set(false)
    generateModelTests.set(false)

    mustRunAfter(downloadEsiSwaggerFile)
}

// Download the ESI swagger file
val downloadEsiSwaggerFile = tasks.register<de.undercouch.gradle.tasks.download.Download>("downloadEsiSwaggerFile") {
    src(esiSwaggerUrl)
    dest(esiSwaggerFile)
}

// Re-download the ESI swagger file and re-generate the Kotlin ESI code
tasks.register("updateEsiApi") {
    group = "eve"
    dependsOn(downloadEsiSwaggerFile, generateEsiApi)
}

// Add the generated code to the source sets, so dependent projects get it
kotlin {
    sourceSets {
        commonMain {
            kotlin.srcDirs(esiSwaggerApiSourcePath)
        }
    }
}