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

import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.nio.file.Path

private val logger: Logger = LoggerFactory.getLogger("libeufin-config")

sealed interface ServerConfig {
    data class Unix(val path: Path): ServerConfig
    data class Tcp(val addr: String, val port: Int): ServerConfig
}

fun TalerConfig.loadServerConfig(section: String): ServerConfig {
    val sect = section(section)
    return sect.mapLambda("serve", "server method", mapOf(
        "tcp" to { ServerConfig.Tcp(sect.string("address").orNull() ?: sect.string("bind_to").require(), sect.number("port").require()) },
        "unix" to { ServerConfig.Unix(sect.path("unixpath").require()) }
    )).require()
}

fun TalerConfigSection.requireAuthMethod(): AuthMethod {
    return mapLambda("auth_method", "auth method", mapOf(
        "none" to { AuthMethod.None },
        "bearer-token" to {
            logger.warn("Deprecated auth method option 'auth_method' used deprecated value 'bearer-token'")
            val token = string("auth_bearer_token").require()
            AuthMethod.Bearer(token)
        },
        "bearer" to {
            val token = string("token").require()
            AuthMethod.Bearer(token)
        },
        "basic" to {
            val username = string("username").require()
            val password = string("password").require()
            AuthMethod.Basic("$username:$password".encodeBase64())
        }
    )).require()
}

sealed interface AuthMethod {
    data object None: AuthMethod
    data class Bearer(val token: String): AuthMethod
    data class Basic(val token: String): AuthMethod
}