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

import okhttp3.HttpUrl.Companion.toHttpUrl
import org.junit.Assert.assertEquals
import org.junit.Test

/**
 * Unit tests for retargeting a sentinel-hosted request onto the configured base
 * URL (PLAN.md §3). Covers the base-path-prefix case that a naive host swap gets
 * wrong.
 */
class HostRewriteTest {

    private fun rewrite(base: String, request: String) =
        rewriteOntoBase(base.toHttpUrl(), request.toHttpUrl()).toString()

    @Test fun swapsHostForRootBase() {
        assertEquals(
            "https://shard.example.com/api/v1/public/status",
            rewrite(
                base = "https://shard.example.com/",
                request = "https://runic-gateway.invalid/api/v1/public/status",
            ),
        )
    }

    @Test fun preservesBasePathPrefixWithoutDoubleSlash() {
        assertEquals(
            "https://host.example.com/uo/api/v1/public/status",
            rewrite(
                base = "https://host.example.com/uo/",
                request = "https://runic-gateway.invalid/api/v1/public/status",
            ),
        )
    }

    @Test fun preservesQueryString() {
        assertEquals(
            "https://shard.example.com/api/v1/public/wiki?q=magic",
            rewrite(
                base = "https://shard.example.com/",
                request = "https://runic-gateway.invalid/api/v1/public/wiki?q=magic",
            ),
        )
    }

    @Test fun keepsPortAndScheme() {
        assertEquals(
            "http://127.0.0.1:3000/api/v1/public/status",
            rewrite(
                base = "http://127.0.0.1:3000/",
                request = "https://runic-gateway.invalid/api/v1/public/status",
            ),
        )
    }
}
