import { ALLOWED_LANGUAGES, ALLOWED_MARKETS, DEVELOPMENT_DOMAINS, ENVIRONMENT_ALIASES, MARKETS, WWW_MARKETS, } from "./pn-refined-marketweb-context.constants";
export class RefinedMarketWebContextService {
    href;
    doc;
    constructor(options) {
        this.href = options?.href ?? window.location.href;
        this.doc = options?.doc ?? document;
    }
    resolve() {
        const url = new URL(this.href);
        const market = this.resolveMarket(url);
        const environment = this.resolveEnvironment(url);
        const language = this.resolveLanguage(market);
        return {
            market,
            environment,
            language,
        };
    }
    getMarket() {
        return this.resolve().market;
    }
    getEnvironmentName() {
        return this.resolve().environment;
    }
    getLanguage() {
        return this.resolve().language;
    }
    isDevEnvironment() {
        const hostname = new URL(this.href).hostname.toLowerCase();
        return DEVELOPMENT_DOMAINS.some(fragment => hostname.includes(fragment));
    }
    getEndpoint(environment, market) {
        if (environment === 'localhost') {
            return '';
        }
        const currentHostname = new URL(this.href).hostname.toLowerCase();
        const config = MARKETS[market];
        if (environment === 'production' && currentHostname === config.live.toLowerCase()) {
            return `https://${config.live}`;
        }
        if (environment !== 'production' && currentHostname === config[environment].toLowerCase()) {
            return `https://${config[environment]}`;
        }
        if (environment === 'production') {
            if (WWW_MARKETS.includes(market)) {
                return `https://${config.live}`;
            }
            if (market === 'tpl') {
                return 'https://www.tpl.postnord.com';
            }
            return `https://${config.live}`;
        }
        return `https://${config[environment]}`;
    }
    resolveEnvironment(url) {
        const hostname = url.hostname.toLowerCase();
        const matchedAlias = Object.keys(ENVIRONMENT_ALIASES).find(alias => hostname.includes(`-${alias}`));
        if (matchedAlias) {
            return ENVIRONMENT_ALIASES[matchedAlias];
        }
        const isKnownLiveHost = Object.values(MARKETS).some(config => config.live.toLowerCase() === hostname);
        if (isKnownLiveHost || hostname.includes('www.')) {
            return 'production';
        }
        return 'integration';
    }
    resolveMarket(url) {
        const hostname = url.hostname.toLowerCase();
        const fromLiveDomain = this.resolveMarketFromLiveDomain(hostname);
        if (fromLiveDomain)
            return fromLiveDomain;
        const fromEnvironmentHost = this.resolveMarketFromEnvironmentHost(hostname);
        if (fromEnvironmentHost)
            return fromEnvironmentHost;
        const fromPostnordSubdomain = this.resolveMarketFromPostnordSubdomain(hostname);
        if (fromPostnordSubdomain)
            return fromPostnordSubdomain;
        if (this.isDevEnvironment()) {
            const fromDevUrl = this.resolveMarketFromDevelopmentUrl(url);
            if (fromDevUrl)
                return fromDevUrl;
        }
        return 'se';
    }
    resolveLanguage(market) {
        const candidates = [
            this.doc?.documentElement?.getAttribute('lang'),
            this.doc?.querySelector('meta[http-equiv="content-language"]')?.getAttribute('content'),
            this.doc?.querySelector('meta[property="og:locale"]')?.getAttribute('content'),
            this.doc?.querySelector('[lang]')?.getAttribute('lang'),
        ];
        for (const candidate of candidates) {
            const normalized = this.normalizeLanguage(candidate);
            if (normalized) {
                return normalized;
            }
        }
        return MARKETS[market].fallbackLanguage;
    }
    normalizeLanguage(value) {
        if (!value) {
            return undefined;
        }
        const normalized = value.trim().toLowerCase().split(/[-_]/)[0];
        return ALLOWED_LANGUAGES.includes(normalized)
            ? normalized
            : undefined;
    }
    resolveMarketFromLiveDomain(hostname) {
        const matched = Object.entries(MARKETS).find(([, config]) => config.live.toLowerCase() === hostname);
        return matched?.[0];
    }
    resolveMarketFromEnvironmentHost(hostname) {
        const matched = Object.entries(MARKETS).find(([, config]) => [config.integration, config.preproduction, config.production].some(envHost => envHost.toLowerCase() === hostname));
        return matched?.[0];
    }
    resolveMarketFromPostnordSubdomain(hostname) {
        if (hostname.includes('www')) {
            return undefined;
        }
        if (!hostname.includes('.postnord.')) {
            return undefined;
        }
        const postnordIndex = hostname.indexOf('.postnord.');
        const beforePostnord = hostname.substring(0, postnordIndex);
        const parts = beforePostnord.split('.').filter(Boolean);
        if (parts.length === 0) {
            return undefined;
        }
        const closestSubdomain = parts[parts.length - 1];
        return this.isMarketName(closestSubdomain) ? closestSubdomain : undefined;
    }
    resolveMarketFromDevelopmentUrl(url) {
        const target = `${url.hostname}${url.pathname}`.toLowerCase();
        const matchedMarket = ALLOWED_MARKETS.find(market => {
            const patterns = [
                `/${market}/`,
                `/${market}`,
                `.${market}.`,
                `.${market}/`,
                `${market}.`,
            ];
            return patterns.some(pattern => target.includes(pattern));
        });
        if (matchedMarket) {
            return matchedMarket;
        }
        const matchedByFallbackLanguage = Object.entries(MARKETS).find(([, config]) => {
            const language = config.fallbackLanguage.toLowerCase();
            const patterns = [
                `/${language}/`,
                `/${language}`,
                `.${language}.`,
                `.${language}/`,
                `${language}.`,
            ];
            return patterns.some(pattern => target.includes(pattern));
        });
        return matchedByFallbackLanguage?.[0];
    }
    isMarketName(value) {
        return ALLOWED_MARKETS.includes(value);
    }
}
//# sourceMappingURL=pn-refined-marketweb-context.service.js.map
