//
//  URLNavigator.swift

//
//  Created by Leon on 2025/7/13.
//

import Foundation
import UIKit
import URLMatcher
import URLNavigator

enum NavigationMap {
    static func initialize(navigator: NavigatorProtocol) {
        navigator.register("http://<path:_>", webViewControllerFactory)
        navigator.register("https://<path:_>", webViewControllerFactory)
        
        navigator.handle("\(AppConst.schemePrefix)alert", alert(navigator: navigator))

        navigator.handle("\(AppConst.schemePrefix)aichat/<aiId>") { url, values, _ -> Bool in
            dlog("[Navigator] NavigationMap.\(url) \(#function):\(#line) - global fallback function is called")
            guard let userIdStr = values["aiId"] as? String, let userId = Int(userIdStr) else {
                return false
            }

//            let tmpUrl = url.urlStringValue.replacingOccurrences(of: AppConst.schemePrefix, with: "https://")
//            if let url = URL(string: tmpUrl), let components = URLComponents(url: url, resolvingAgainstBaseURL: true) {
//                if let queryItems = components.queryItems {
//                    for item in queryItems {
//                        // print("\(item.name): \(String(describing: item.value))")
//                        if item.name == "productId", let idStr = item.value, let id = Int(idStr) {
//                            // ..
//                        }
//                    }
//                }
//            }
            if UserCore.shared.isLogin(){
                AppRouter.goChatVC(aiId: userId)
            }else{
                AppRouter.goAIRoleHome(aiId: userId)
            }

            // AppRouter.goPersonalPageController(userId: userId, productId: productId)
            return true
        }

        navigator.handle("\(AppConst.schemePrefix)route/<uri>") { (url, values: [String: Any], _) -> Bool in
            dlog("[Navigator] NavigationMap.\(url) \(#function):\(#line) - global fallback function is called")
            guard let uri = values["uri"] as? String else {
                return false
            }
            if uri == "report" {
                // ...
            }

            return true
        }
    }

    // MARK: -  helper

    func convertQueryParams(urlstr: URLConvertible) -> [URLQueryItem] {
        guard let urlPath = urlstr.urlStringValue as? String else {
            return []
        }
        // var dict: Dictionary?
        var allkeysValues = [String: Any]()
        if let url = URL(string: urlPath), let components = URLComponents(url: url, resolvingAgainstBaseURL: true) {
            if let queryItems = components.queryItems {
                return queryItems
            }
        }

        return []
    }

    // MARK: - factory

    private static func webViewControllerFactory(
        url: URLConvertible,
        values: [String: Any],
        context: Any?
    ) -> UIViewController? {
        guard let url = url.urlValue else { return nil }
        let h5 = H5Controller()
        h5.loadURL(url: url)
        return h5
    }

    // MARK: - other

    private static func alert(navigator: NavigatorProtocol) -> URLOpenHandlerFactory {
        return { url, _, _ in
            guard let title = url.queryParameters["title"] else { return false }
            let message = url.queryParameters["message"]
            let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
            alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
            navigator.present(alertController, wrap: nil, from: nil, animated: true, completion: nil)
            return true
        }
    }
}
