package net.hivetechnology.o20010_06

import java.net.URI

internal const val MOBILE_VPN_COMPANION_URL =
    "https://portal.hivetechnology.net/mobile-vpn?platform=android"

private val portalActionPhases = setOf("idle", "stopped", "failed", "cancelled")

internal fun shouldShowPortalAction(phase: String): Boolean = phase in portalActionPhases

internal fun mobileVpnPortalDestination(value: String?): String =
    validatedMobileVpnPortalUrl(value) ?: MOBILE_VPN_COMPANION_URL

internal fun validatedMobileVpnPortalUrl(value: String?): String? = runCatching {
    val candidate = URI(value ?: return null)
    val path = candidate.normalize().path
    if (candidate.scheme != "https" || candidate.host != "portal.hivetechnology.net" ||
        candidate.userInfo != null || (candidate.port != -1 && candidate.port != 443) ||
        (path != "/mobile-vpn" && !path.startsWith("/mobile-vpn/"))
    ) return null
    candidate.toASCIIString()
}.getOrNull()
