/*
 * This file is part of LibEuFin.
 * Copyright (C) 2024-2025 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.nexus.cli

import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.core.Context
import com.github.ajalt.clikt.core.ProgramResult
import com.github.ajalt.clikt.parameters.groups.provideDelegate
import com.github.ajalt.clikt.parameters.options.flag
import com.github.ajalt.clikt.parameters.options.option
import tech.libeufin.common.TalerCmd
import tech.libeufin.common.api.serve
import tech.libeufin.nexus.nexusApi
import tech.libeufin.nexus.nexusConfig
import tech.libeufin.nexus.withDb


class Serve : TalerCmd("serve") {
    override fun help(context: Context) = "Run libeufin-nexus HTTP server"

    private val check by option(
        help = "Check whether an API is in use (if it's useful to start the HTTP server). Exit with 0 if at least one API is enabled, otherwise 1"
    ).flag()

    override fun run() = cliCmd(logger) {
        val cfg = nexusConfig(config)
        
        if (check) {
            // Check if the server is to be started
            val apis = listOf(
                cfg.wireGatewayApiCfg to "Wire Gateway API",
                cfg.revenueApiCfg to "Revenue API"
            )
            var startServer = false
            for ((api, name) in apis) {
                if (api != null) {
                    startServer = true
                    logger.info("$name is enabled: starting the server")
                }
            }
            if (!startServer) {
                logger.info("All APIs are disabled: not starting the server")
                throw ProgramResult(1)
            } else {
                throw ProgramResult(0)
            }
        }

        cfg.withDb { db, cfg ->
            serve(cfg.serverCfg, logger) {
                nexusApi(db, cfg)
            }
        }
    }
}