import Foundation

/// Resolves widget action paths (including Gmail `{{u}}` account slots) against an app base URL.
enum WidgetDeepLinkURL {
    static func resolved(base: URL, actionPath: String?, accountSlot: Int) -> URL {
        guard let actionPath, !actionPath.isEmpty else { return base }
        let substituted = actionPath.replacingOccurrences(of: "{{u}}", with: "\(accountSlot)")
        if substituted.hasPrefix("http://") || substituted.hasPrefix("https://") {
            return URL(string: substituted) ?? base
        }
        if substituted.lowercased().hasPrefix("mailto:") {
            return URL(string: substituted) ?? base
        }
        if substituted.hasPrefix("/") {
            var c = URLComponents(url: base, resolvingAgainstBaseURL: false)
            let pathAndQuery: String
            let fragmentPart: String?
            if let hashIdx = substituted.firstIndex(of: "#") {
                pathAndQuery = String(substituted[..<hashIdx])
                fragmentPart = String(substituted[substituted.index(after: hashIdx)...])
            } else {
                pathAndQuery = substituted
                fragmentPart = nil
            }
            if let qIdx = pathAndQuery.firstIndex(of: "?") {
                let pathPart = String(pathAndQuery[..<qIdx])
                let queryPart = String(pathAndQuery[pathAndQuery.index(after: qIdx)...])
                c?.path = pathPart
                c?.query = queryPart
            } else {
                c?.path = pathAndQuery
            }
            if let fragmentPart, !fragmentPart.isEmpty {
                c?.fragment = String(fragmentPart)
            } else {
                c?.fragment = nil
            }
            return c?.url ?? base
        }
        return URL(string: substituted, relativeTo: base)?.absoluteURL ?? base
    }
}
