package app.voltplan.cable.affiliate

import android.net.Uri

/** Builds locale-aware Amazon search URLs with affiliate tags. Direct port of `AmazonAffiliate`. */
object AmazonAffiliate {
    private const val FALLBACK_DOMAIN = "www.amazon.com"
    private const val FALLBACK_TAG = "voltplan-20"

    private val domainsByCountry = mapOf(
        "US" to "www.amazon.com", "DE" to "www.amazon.de", "FR" to "www.amazon.fr",
        "ES" to "www.amazon.es", "IT" to "www.amazon.it", "GB" to "www.amazon.co.uk",
        "CA" to "www.amazon.ca", "JP" to "www.amazon.co.jp", "AU" to "www.amazon.com.au",
        "NL" to "www.amazon.nl", "SE" to "www.amazon.se", "PL" to "www.amazon.pl",
        "MX" to "www.amazon.com.mx", "BR" to "www.amazon.com.br", "IN" to "www.amazon.in",
    )

    private val tagsByCountry = mapOf(
        "US" to "voltplan-20", "DE" to "voltplan-21", "AU" to "voltplan-22",
        "GB" to "voltplan00-21", "FR" to "voltplan0f-21", "CA" to "voltplan01-20",
    )

    private val aliases = mapOf("UK" to "GB")

    private fun normalize(countryCode: String?): String? {
        val upper = countryCode?.uppercase()?.trim()
        if (upper.isNullOrEmpty()) return null
        return aliases[upper] ?: upper
    }

    private fun domain(countryCode: String?): String {
        val code = normalize(countryCode) ?: return FALLBACK_DOMAIN
        return domainsByCountry[code] ?: FALLBACK_DOMAIN
    }

    private fun tag(countryCode: String?): String {
        val code = normalize(countryCode) ?: return FALLBACK_TAG
        return tagsByCountry[code] ?: FALLBACK_TAG
    }

    fun searchUrl(query: String, countryCode: String?): String? {
        if (query.isBlank()) return null
        val builder = Uri.Builder()
            .scheme("https")
            .authority(domain(countryCode))
            .path("/s")
            .appendQueryParameter("k", query)
        tag(countryCode).takeIf { it.isNotEmpty() }?.let { builder.appendQueryParameter("tag", it) }
        return builder.build().toString()
    }
}
