import Foundation
import CryptoKit

extension SignedMessage {

    /// The message encoded to data
    var encoded: Data {
        mac + message.encoded
    }

    var bytes: [UInt8] {
        Array(encoded)
    }

    /**
     Create a message from received bytes.
     - Parameter data: The sequence of bytes
     - Note: The sequence must contain at least `Message.length` bytes, or the function will crash.
     */
    init(decodeFrom data: Data) throws {
        guard data.count == SignedMessage.size else {
            print("Invalid signed message size \(data.count)")
            throw MessageResult.invalidMessageSizeFromDevice
        }
        let count = SHA256.byteCount
        self.mac = data.prefix(count)
        self.message = try Message(decodeFrom: data.dropFirst(count))
    }

    /**
     Check if the message contains a valid authentication code
     - Parameter key: The key used to sign the message.
     - Returns: `true`, if the message is valid.
     */
    func isValid(using key: SymmetricKey) -> Bool {
         HMAC<SHA256>.isValidAuthenticationCode(mac, authenticating: message.encoded, using: key)
    }
}
