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

import kotlinx.serialization.Serializable
import tech.libeufin.common.*

@JvmInline
value class Password(val pw: String)

// NIST Password Guidelines 2024
private const val PASSWORD_MIN_LEN = 8
private const val PASSWORD_MAX_LEN = 64

/** Check if a string is a valid password */
fun String.checkPw(checkQuality: Boolean): Password {
    if (!checkQuality) return Password(this)
    val len = this.length
    return when {
        len < PASSWORD_MIN_LEN -> throw conflict(
            "Password is too short, expect at least ${PASSWORD_MIN_LEN} characters got ${len}",
            TalerErrorCode.BANK_PASSWORD_TOO_SHORT
        )
        len > PASSWORD_MAX_LEN -> throw conflict(
            "Password is too long, expect at most ${PASSWORD_MAX_LEN} characters got ${len}",
            TalerErrorCode.BANK_PASSWORD_TOO_LONG
        )
        else -> Password(this)
    }
}

data class PasswordHashCheck(
    val match: Boolean,
    val outdated: Boolean
)

/** Cryptographic operations for secure password storage and verification */
sealed interface PwCrypto {
    @Serializable
    data class Bcrypt(val cost: Int = 8): PwCrypto

    /** Hash [pw] using [cfg] hashing method */
    fun hashpw(pw: String): String {
        when (this) {
            is Bcrypt -> {
                val salt = ByteArray(16).secureRand()
                val pwh = CryptoUtil.bcrypt(pw, salt, cost)
                return "bcrypt\$$cost\$${salt.encodeBase64()}\$${pwh.encodeBase64()}"
            }
            /* TODO Argon2id 
            "argon2id" -> {
                require(components.size == 3) { "bad password hash format" }
                val salt = components[1].decodeBase64()
                val hash = components[2]
                val pwh = CryptoUtil.hashArgon2id(pw, salt).encodeBase64()
                PasswordHashCheck(pwh == hash, false)
            } */
        }
    }

    /** Check whether [pw] match hashed [storedPwHash] and if it should be rehashed */
    fun checkpw(pw: String, storedPwHash: String): PasswordHashCheck {
        val components = storedPwHash.split('$', limit = 5)
        return when (val algo = components[0]) {
            "sha256" -> {
                require(components.size == 2) { "bad password hash format" }
                val hash = components[1]
                val pwh = CryptoUtil.hashStringSHA256(pw).encodeBase64()
                PasswordHashCheck(pwh == hash, true)
            }
            "sha256-salted" -> {
                require(components.size == 3) { "bad password hash format" }
                val salt = components[1]
                val hash = components[2]
                val pwh = CryptoUtil.hashStringSHA256("$salt|$pw").encodeBase64()
                PasswordHashCheck(pwh == hash, true)
            }
            "bcrypt" -> {
                require(components.size == 4) { "bad password hash format" }
                val cost = components[1].toInt()
                val salt = components[2].decodeBase64()
                val hash = components[3]
                val pwh = CryptoUtil.bcrypt(pw, salt, cost).encodeBase64()
                PasswordHashCheck(pwh == hash, !(this is Bcrypt && this.cost == cost))
            }
            else -> throw Exception("unsupported hash algo: '$algo'")
        }
    }
}