const defaultDomainNames = ['komi', 'localhost'];
const defaultDomainEnvs = [
    'local',
    'develop',
    'staging',
    'preprod',
    'production'
];
const getLastDomainNameIndex = (url, domainNames = defaultDomainNames) => {
    const domainParts = getDomainParts(url);
    let lastDomainNameIndex = -1;
    for (let i = 0; i < domainParts.length; i++) {
        const domainPart = domainParts[i];
        if (domainNames.includes(domainPart)) {
            lastDomainNameIndex = i;
        }
    }
    return lastDomainNameIndex;
};
export const getDomainParts = (url) => {
    const { hostname } = new URL(url);
    return hostname.split('.');
};
export const getRootDomain = (url, domainNames = defaultDomainNames) => {
    const domainNameIndex = getLastDomainNameIndex(url, domainNames);
    if (domainNameIndex === -1) {
        throw new Error(`URL '${url}' does not contain a known domain name`);
    }
    const domainParts = getDomainParts(url);
    const rootDomainParts = domainParts.slice(domainNameIndex);
    return rootDomainParts.join('.');
};
export const getEnvRootDomain = (url, domainNames = defaultDomainNames, domainEnvs = defaultDomainEnvs) => {
    const domainNameIndex = getLastDomainNameIndex(url, domainNames);
    if (domainNameIndex === -1) {
        throw new Error(`URL '${url}' does not contain a known domain name`);
    }
    const domainParts = getDomainParts(url);
    const domainEnvIndex = domainNameIndex - 1;
    const isDomainEnvPresent = domainEnvIndex > -1 && domainEnvs.includes(domainParts[domainEnvIndex]);
    const rootDomainParts = domainParts.slice(isDomainEnvPresent ? domainEnvIndex : domainNameIndex);
    return rootDomainParts.join('.');
};
export const getRootDomainWithPort = (url, domainNames = defaultDomainNames) => {
    const { port } = new URL(url);
    const portAppendage = port.length === 0 ? '' : `:${port}`;
    return `${getRootDomain(url, domainNames)}${portAppendage}`;
};
