#if canImport(Network)
import Foundation
import Network
import Security
import X509
import _CryptoExtras

/// Turns a CA-issued server leaf (cert + RSA key) into the `sec_identity_t` an `NWListener` needs for
/// TLS (docs/MACOS_VM_MDM.md §4). We already have a verified PKCS#12 encoder, so the path is: export
/// the server identity as a transient PKCS#12 → `SecPKCS12Import` → `SecIdentity` → `sec_identity_t`.
/// This also runs our PKCS#12 through Apple's own parser, a second real-format check beyond openssl.
public enum MDMTLSIdentity {
    public enum TLSError: Error, CustomStringConvertible {
        case importFailed(OSStatus)
        case noIdentity
        public var description: String {
            switch self {
            case .importFailed(let s): return "SecPKCS12Import failed (OSStatus \(s))"
            case .noIdentity: return "PKCS#12 import returned no identity"
            }
        }
    }

    /// Build a `sec_identity_t` for the server leaf. `password` is a throwaway used only to move the
    /// identity through the PKCS#12 import (never leaves this process).
    public static func serverIdentity(
        certificate: Certificate, privateKey: _RSA.Signing.PrivateKey,
        password: String = MDMDeviceIdentity.randomPassword()
    ) throws -> sec_identity_t {
        let p12 = try PKCS12.export(
            certificate: certificate, privateKey: privateKey, password: password)
        let options = [kSecImportExportPassphrase as String: password] as CFDictionary
        var items: CFArray?
        let status = SecPKCS12Import(p12 as CFData, options, &items)
        guard status == errSecSuccess else { throw TLSError.importFailed(status) }
        guard
            let array = items as? [[String: Any]], let first = array.first,
            let identityAny = first[kSecImportItemIdentity as String]
        else { throw TLSError.noIdentity }
        let secIdentity = identityAny as! SecIdentity
        guard let secId = sec_identity_create(secIdentity) else { throw TLSError.noIdentity }
        return secId
    }
}
#endif
