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

import io.ktor.server.application.*
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import tech.libeufin.ebics.*
import tech.libeufin.ebisync.*
import tech.libeufin.ebisync.db.Database
import tech.libeufin.ebisync.api.*
import tech.libeufin.common.*
import tech.libeufin.common.api.*
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 java.nio.file.Path


class Serve : TalerCmd() {
    override fun help(context: Context) = "Run libeufin-ebisync 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()
    val ebicsLog by ebicsLogOption()

    override fun run() = cliCmd(logger) {
        val cfg = ebisyncConfig(config)
        val auth = when (val source = cfg.submit.source) {
            Source.None -> null
            is Source.SyncAPI -> source.auth
        }
        if (check) {
            if (auth == null) {
                logger.info("No source api, not starting the server")
                throw ProgramResult(1)
            } else {
                throw ProgramResult(0)
            }
        } else if (auth == null) {
            throw ProgramResult(0)
        }

        cfg.withDb { db, cfg ->
            val (clientKeys, bankKeys) = expectFullKeys(cfg)
            val client = EbicsClient(
                cfg,
                httpClient(),
                db.ebics,
                EbicsLogger(ebicsLog),
                clientKeys,
                bankKeys
            )
            serve(cfg.serverCfg, logger) {
                ebisyncApi(auth, client, cfg.spa)
            }
        }
    }
}