//
//  CommonViewController.swift
//  DNSResolverDemo
//
//  Created by issuser on 2025/9/2.
//

import UIKit
import Foundation

class CommonViewController: UIViewController, URLSessionDelegate,URLSessionTaskDelegate {
    
    private var mutableReq: NSMutableURLRequest?
    private var resultTextView: UITextView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .white
        title = "普通场景"
        
        createUI()
        
        let domain = "www.baidu.com"
        // let domain = "m.jtexpress.com.cn" // SNI场景
        // let domain = "www.douyin.com"     // SNI场景
        
        // 方式一：异步解析 IP
        DNSResolver.share().getIpsData(withDomain: domain) { [weak self] dataArray in
            guard let self = self else { return }
            let ip = dataArray?.first ?? domain
            
            // 温馨提示：请添加兜底处理（使用域名）
            self.request(withIP: ip, domain: domain)
        }
        
        // 方式二：从缓存获取（可选）
        /*
        let array = DNSResolver.shared.getIpsByCache(withDomain: domain, andExpiredIPEnabled: true)
        let ip = array.first ?? domain
        self.request(withIP: ip, domain: domain)
        */
    }
    
    private func createUI() {
        resultTextView = UITextView(frame: CGRect(x: 0, y: 200, width: UIScreen.main.bounds.width, height: 200))
        resultTextView.backgroundColor = .lightGray
        view.addSubview(resultTextView)
    }
    
    // MARK: - 普通场景请求
    private func request(withIP ip: String, domain: String) {
//        // 注意：这里使用了硬编码 URL，实际中应拼接 ip 和 path
//        guard let httpDnsURL = URL(string: "https://47.107.180.216:443/fapi/config/public/app/base/setting") else {
//            print("Invalid URL")
//            return
//        }
        guard let httpDnsURL = URL(string: "https://\(ip)") else {
            print("Invalid IP address: \(ip)")
            return
        }
        
        let mutableReq = NSMutableURLRequest(url: httpDnsURL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10)
        mutableReq.setValue(domain, forHTTPHeaderField: "Host") // 设置 Host 为原始域名
        self.mutableReq = mutableReq
        
        let config = URLSessionConfiguration.default
        let session = URLSession(configuration: config, delegate: self, delegateQueue: .current)
        
        let task = session.dataTask(with: mutableReq as URLRequest) { [weak self] data, response, error in
            guard let self = self else { return }
            
            if let error = error {
                print("_________error: \(error)")
                return
            }
            
            if let data = data, let string = String(data: data, encoding: .utf8) {
                print("_________response: \(string)")
                DispatchQueue.main.async {
                    self.resultTextView.text = string
                }
            }
            
            session.finishTasksAndInvalidate()
        }
        
        task.resume()
    }
    
    // MARK: - URLSession Delegate
    /*
    // 绕过证书验证（仅用于测试，生产环境不推荐）
    func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust,
           let serverTrust = challenge.protectionSpace.serverTrust {
            let credential = URLCredential(trust: serverTrust)
            completionHandler(.useCredential, credential)
        } else {
            completionHandler(.performDefaultHandling, nil)
        }
    }
    */
    
    
     // 如果需要更严格的证书校验（如绑定域名），可以启用以下方法
    func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        
        guard let mutableReq = self.mutableReq else {
            completionHandler(.performDefaultHandling, nil)
            return
        }
        
        // 获取原始 Host 域名
        var host = mutableReq.allHTTPHeaderFields?["Host"]
        if host == nil || host!.isEmpty {
            host = mutableReq.url?.host
        }
        
        if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust,
           let serverTrust = challenge.protectionSpace.serverTrust {
            
            let disposition: URLSession.AuthChallengeDisposition
            let credential: URLCredential?
            
            if evaluate(serverTrust: serverTrust, forDomain: host ?? "") {
                disposition = .useCredential
                credential = URLCredential(trust: serverTrust)
            } else {
                disposition = .performDefaultHandling
                credential = nil
            }
            
            completionHandler(disposition, credential)
        } else {
            completionHandler(.performDefaultHandling, nil)
        }
    }
    
    private func evaluate(serverTrust: SecTrust, forDomain domain: String) -> Bool {
        let policies = domain.isEmpty ? [SecPolicyCreateBasicX509()] : [SecPolicyCreateSSL(true, domain as CFString)]
        SecTrustSetPolicies(serverTrust, policies as CFArray)
        
        var result = SecTrustResultType.invalid
        SecTrustEvaluate(serverTrust, &result)
        
        return result == .unspecified || result == .proceed
    }
    
}
