/*
 * This file is part of LibEuFin.
 * Copyright (C) 2023, 2024, 2025, 2026 Taler Systems S.A.

 * LibEuFin is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation; either version 3, or
 * (at your option) any later version.

 * LibEuFin is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General
 * Public License for more details.

 * You should have received a copy of the GNU Affero General Public
 * License along with LibEuFin; see the file COPYING.  If not, see
 * <http://www.gnu.org/licenses/>
 */

package tech.libeufin.bank

import io.ktor.server.application.*
import io.ktor.server.http.content.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import tech.libeufin.bank.api.*
import tech.libeufin.bank.cli.LibeufinBank
import tech.libeufin.bank.db.Database
import tech.libeufin.common.api.OpenApiInfo
import tech.libeufin.common.api.talerApi
import tech.libeufin.common.VERSION
import com.github.ajalt.clikt.core.main

val logger: Logger = LoggerFactory.getLogger("libeufin-bank")
 
/** Set up web server handlers for the Taler corebank API */
fun Application.corebankWebApp(db: Database, cfg: BankConfig, serveSpec: Boolean = false) = talerApi(
    LoggerFactory.getLogger("libeufin-bank-api"),
    OpenApiInfo(
        title = "LibEuFin Bank API",
        version = VERSION,
        description = "Taler corebank, wire gateway, wire transfer gateway, integration, conversion, revenue, and observability APIs for LibEuFin Bank",
        securityConfig = { 
            securityScheme("bearerAuth") {
                type = io.github.smiley4.ktoropenapi.config.AuthType.HTTP
                scheme = io.github.smiley4.ktoropenapi.config.AuthScheme.BEARER
                bearerFormat = "token"
                description = "Bearer tokens minted by libeufin-bank /accounts/{USERNAME}/token"
            }
            securityScheme("basicAuth") {
                type = io.github.smiley4.ktoropenapi.config.AuthType.HTTP
                scheme = io.github.smiley4.ktoropenapi.config.AuthScheme.BASIC
                description = "HTTP Basic authentication, supported only on compatibility-enabled endpoints"
            }
        }
    ),
    serveSpec = serveSpec
) {
    coreBankApi(db, cfg)
    conversionApi(db, cfg)
    bankIntegrationApi(db, cfg)
    wireGatewayApi(db, cfg)
    preparedTransferApi(db, cfg)
    revenueApi(db, cfg)
    observabilityApi(db, cfg)
    cfg.spaPath?.let {
        get("/") {
            call.respondRedirect("/webui/")
        }
        staticFiles("/webui/", it.toFile())
    }
}

fun main(args: Array<String>) {
    LibeufinBank().main(args)
}

