/*
 * SPDX-License-Identifier: GPL-3.0-or-later
 */
package com.runicgateway.app.core.net

import okhttp3.HttpUrl
import java.util.concurrent.atomic.AtomicReference
import javax.inject.Inject
import javax.inject.Singleton

/**
 * Holds the currently-selected shard website base URL (PLAN.md §3). The API host
 * is not compiled in: it is chosen on first run, may be changed later under
 * Settings → Server, and every outbound API request is retargeted onto it by
 * [HostSelectionInterceptor].
 *
 * Threading: the value is read on every network call and written from the
 * connect/settings flows, so it lives in an [AtomicReference].
 */
@Singleton
class BaseUrlHolder @Inject constructor() {
    private val ref = AtomicReference<HttpUrl?>(null)

    /** The configured base, or null before first-run connect completes. */
    val current: HttpUrl? get() = ref.get()

    fun set(url: HttpUrl?) = ref.set(url)

    companion object {
        /**
         * Sentinel host used as Retrofit's compile-time `baseUrl`. Relative
         * endpoint paths resolve against it; [HostSelectionInterceptor] rewrites
         * exactly these requests onto [current]. Absolute-URL probe requests use
         * a real host and are left untouched. `.invalid` is reserved (RFC 6761)
         * so it can never accidentally resolve on a network.
         */
        const val PLACEHOLDER_HOST = "runic-gateway.invalid"
        const val PLACEHOLDER_BASE_URL = "https://$PLACEHOLDER_HOST/"
    }
}
