package com.betriebsratkanzlei.legalconsenthub_middleware.signature

import com.betriebsratkanzlei.legalconsenthub_middleware.smartcard.SmartCardService
import com.betriebsratkanzlei.legalconsenthub_middleware_api.model.VerifySignatureResponseDto
import com.betriebsratkanzlei.legalconsenthub_middleware_api.model.CertificateDto
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.stereotype.Service
import java.util.*

@Service
@ConditionalOnProperty(name = ["dummy.mode.enabled"], havingValue = "false", matchIfMissing = true)
class SignatureService(
    private val smartCardService: SmartCardService
) {

    fun signPdfHash(
        document: ByteArray,
        certificateId: String,
        hashAlgorithm: String
    ): String {
        val hashBase64 = smartCardService.calculateHash(document, hashAlgorithm)

        val certificates = smartCardService.getSmartCardCertificates()
        certificates.find { it.id == certificateId }
            ?: throw IllegalArgumentException("Certificate not found: $certificateId")

        // Sign the hash using smart card (PIN will be entered on device)
        return smartCardService.signHash(hashBase64, certificateId)
    }

    fun verifySignature(
        document: ByteArray,
        signature: String,
        certificateId: String?,
        hashAlgorithm: String
    ): VerifySignatureResponseDto {
        try {
            val certificates = smartCardService.getSmartCardCertificates()
            val certificate = if (certificateId != null) {
                certificates.find { it.id == certificateId }
                    ?: throw IllegalArgumentException("Certificate not found: $certificateId")
            } else {
                // If no specific certificate ID provided, try to find the certificate from the signature
                // For now, we'll use the first available certificate
                certificates.firstOrNull()
                    ?: throw IllegalArgumentException("No certificates available for verification")
            }

            val isValid = smartCardService.verifySignature(document, signature, certificate.id, hashAlgorithm)

            return VerifySignatureResponseDto(
                isValid = isValid,
                certificateInfo = certificate,
                verificationDetails = "Signature verified using pkcs11-tool with ${hashAlgorithm} algorithm"
            )

        } catch (e: Exception) {
            return VerifySignatureResponseDto(
                isValid = false,
                certificateInfo = null,
                verificationDetails = "Verification failed: ${e.message}"
            )
        }
    }
}
