import Foundation

/// C-iOS-2 · Reusable `NSObject` URLSession delegate that answers
/// **session-level** auth challenges by delegating to `MutualTLSChallengeResponder`.
///
/// This is the seam for the HTTP transport (`session.data(for:)` surfaces
/// challenges through `urlSession(_:didReceive:completionHandler:)`). The WS
/// transport can't reuse it — its connection object is already the session's
/// delegate and needs the **task-level** callback — so that one implements the
/// task-level method itself against the same responder.
///
/// `@unchecked Sendable`: URLSession retains its delegate and invokes it from
/// arbitrary queues; every stored field is an immutable `let` over thread-safe
/// values (`ClientIdentity` is `@unchecked Sendable`, the responder is stateless).
public final class ClientTLSSessionDelegate: NSObject, URLSessionDelegate, @unchecked Sendable {
    private let identity: ClientIdentity?
    private let responder: MutualTLSChallengeResponder

    public init(
        identity: ClientIdentity?,
        responder: MutualTLSChallengeResponder = MutualTLSChallengeResponder()
    ) {
        self.identity = identity
        self.responder = responder
        super.init()
    }

    public func urlSession(
        _ session: URLSession,
        didReceive challenge: URLAuthenticationChallenge,
        completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void
    ) {
        let resolution = responder.resolve(challenge, identity: identity)
        completionHandler(resolution.disposition, resolution.credential)
    }
}
