import Foundation

enum AmazonAffiliate {
    private static let fallbackDomain = "www.amazon.com"
    private static let fallbackTag: String? = nil

    private static let domainsByCountry: [String: String] = [
        "US": "www.amazon.com",
        "DE": "www.amazon.de",
        "FR": "www.amazon.fr",
        "ES": "www.amazon.es",
        "IT": "www.amazon.it",
        "GB": "www.amazon.co.uk",
        "CA": "www.amazon.ca",
        "JP": "www.amazon.co.jp",
        "AU": "www.amazon.com.au",
        "NL": "www.amazon.nl",
        "SE": "www.amazon.se",
        "PL": "www.amazon.pl",
        "MX": "www.amazon.com.mx",
        "BR": "www.amazon.com.br",
        "IN": "www.amazon.in"
    ]

    // Configure Amazon affiliate tracking IDs by country code.
    private static let tagsByCountry: [String: String] = [
        "US": "voltplan-20",
        "DE": "voltplan-21",
    ]

    private static let countryAliases: [String: String] = [
        "UK": "GB"
    ]

    static func searchURL(query: String, countryCode: String?) -> URL? {
        guard !query.isEmpty else { return nil }

        var components = URLComponents()
        components.scheme = "https"
        components.host = domain(for: countryCode)
        components.path = "/s"

        var queryItems = [URLQueryItem(name: "k", value: query)]
        if let tag = affiliateTag(for: countryCode), !tag.isEmpty {
            queryItems.append(URLQueryItem(name: "tag", value: tag))
        }
        components.queryItems = queryItems

        return components.url
    }

    static func domain(for countryCode: String?) -> String {
        guard let normalized = normalizedCountryCode(from: countryCode) else {
            return fallbackDomain
        }
        return domainsByCountry[normalized] ?? fallbackDomain
    }

    static func affiliateTag(for countryCode: String?) -> String? {
        guard let normalized = normalizedCountryCode(from: countryCode) else {
            return fallbackTag
        }
        return tagsByCountry[normalized] ?? fallbackTag
    }

    private static func normalizedCountryCode(from countryCode: String?) -> String? {
        guard let raw = countryCode?.uppercased(), !raw.isEmpty else { return nil }
        if let alias = countryAliases[raw] {
            return alias
        }
        return raw
    }
}
