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

import tech.libeufin.common.*
import tech.libeufin.common.db.*
import java.time.Instant

/** Data access logic for transfer specific logic */
class TransferDAO(private val db: Database) {
    /** Result of prepared transfer registration */
    sealed interface RegistrationResult {
        data object Success: RegistrationResult
        data object ReservePubReuse: RegistrationResult
        data object SubjectReuse: RegistrationResult
    }

    /** Register a prepared transfer */
    suspend fun register(
        type: TransferType,
        accountPub: EddsaPublicKey,
        authPub: EddsaPublicKey,
        authSig: EddsaSignature,
        recurrent: Boolean,
        referenceNumber: String?,
        timestamp: Instant
    ): RegistrationResult = db.serializable(
        """
        SELECT
            out_subject_reuse
            ,out_reserve_pub_reuse
        FROM register_prepared_transfers (
            ?::taler_incoming_type, ?, ?, ?, ?, ?, ?
        )
        """
    ) {
        bind(type)
        bind(accountPub)
        bind(authPub)
        bind(authSig)
        bind(recurrent)
        bind(referenceNumber)
        bind(timestamp)
        one {
            when {
                it.getBoolean("out_subject_reuse") -> RegistrationResult.SubjectReuse
                it.getBoolean("out_reserve_pub_reuse") -> RegistrationResult.ReservePubReuse
                else -> RegistrationResult.Success
            }
        }
    }

    /** Unregister a prepared transfer */
    suspend fun unregister(
        authorizationPub: EddsaPublicKey,
        timestamp: Instant
    ) = db.serializable(
        "SELECT out_found FROM delete_prepared_transfers(?,?)",
        {
            bind(authorizationPub)
            bind(timestamp)
            one {
                it.getBoolean(1)
            }
        }
    )
}