package com.ponzischeme89.memby.data

import com.ponzischeme89.memby.BuildConfig

/**
 * Where this build gets its data.
 *
 * Two addresses are baked in at build time (see gradle.properties):
 *
 *  - `memby.gatewayUrl` — the Memby gateway container. When set, the client is a thin
 *    renderer: the gateway owns auth, caching, search and screen shaping.
 *  - `memby.serverUrl` — the Emby server, used directly when no gateway is configured.
 *    Keeping this path alive means a gateway outage is a config change away from being
 *    routed around, and it is what the app falls back to during the migration.
 *
 * Neither is typed on a TV remote; both are properties of the build.
 */
object ServerConfig {

    /** The Memby gateway, normalised, or null when this build talks to Emby directly. */
    val gatewayUrl: String? =
        BuildConfig.MEMBY_GATEWAY_URL.trim()
            .takeIf { it.isNotBlank() }
            ?.let(::normalizeServerUrl)

    /** The hardwired Emby server, normalised, or null when this build doesn't pin one. */
    val hardwiredUrl: String? =
        BuildConfig.EMBY_SERVER_URL.trim()
            .takeIf { it.isNotBlank() }
            ?.let(::normalizeServerUrl)

    val isGateway: Boolean get() = gatewayUrl != null

    val isHardwired: Boolean get() = hardwiredUrl != null

    /** The address this build actually signs in against. */
    val backendUrl: String? get() = gatewayUrl ?: hardwiredUrl

    /** Host (and port) of that address, for display on the setup screen. */
    val displayHost: String?
        get() = backendUrl?.substringAfter("://")?.trimEnd('/')
}

/**
 * Resolves the server to use: the hardwired address when this build pins one, otherwise
 * whatever the user typed. Returns null when neither is available.
 */
fun resolveServerUrl(hardwired: String?, entered: String): String? = when {
    !hardwired.isNullOrBlank() -> normalizeServerUrl(hardwired)
    entered.isNotBlank() -> normalizeServerUrl(entered)
    else -> null
}
