import Foundation
import SwiftUI

@Observable
final class VerificationVM {
    var safetyNumber: String?
    var myFingerprint: String?
    var peerFingerprint: String?
    var verificationStatus: String = "unverified"  // "verified", "trusted", "unverified"
    var qrCodeData: Data?
    var scanResult: String?
    var scanSuccess: Bool?
    var isLoading = false
    var errorMessage: String?

    func loadVerification(peerUserId: String, chatClient: ChatClient) async {
        isLoading = true

        // Ensure peer's identity key is fetched (needed for safety number & verification)
        _ = await chatClient.getPeerIdentityKey(userId: peerUserId)

        // Get safety number
        safetyNumber = await chatClient.getSafetyNumber(peerUserId: peerUserId)

        // Get fingerprints
        myFingerprint = await chatClient.getMyFingerprint()
        peerFingerprint = await chatClient.getPeerFingerprint(peerUserId: peerUserId)

        // Get verification status
        verificationStatus = await chatClient.getVerificationStatus(userId: peerUserId)

        // Get QR code data for display
        qrCodeData = await chatClient.getVerificationQRData()

        isLoading = false
    }

    func verifyContact(peerUserId: String, chatClient: ChatClient) async {
        guard let peerIK = await chatClient.getPeerIdentityKey(userId: peerUserId) else {
            errorMessage = "No identity key on record for this user."
            return
        }
        await chatClient.verifyContact(userId: peerUserId, identityKey: peerIK, method: "manual")
        verificationStatus = "verified"
    }

    func unverifyContact(peerUserId: String, chatClient: ChatClient) async {
        await chatClient.unverifyContact(userId: peerUserId)
        verificationStatus = "trusted"
    }

    func verifyQRCode(data: Data, chatClient: ChatClient) async {
        let (success, _, message) = await chatClient.verifyQRCode(qrData: data)
        scanSuccess = success
        scanResult = message
        if success {
            verificationStatus = "verified"
        }
    }
}
