"use strict";
/* eslint-disable @typescript-eslint/no-explicit-any */
Object.defineProperty(exports, "__esModule", { value: true });
const url_1 = require("url");
const index_1 = require("./index");
const parseAs = (originalAs, href) => {
    const asType = typeof originalAs;
    let as;
    if (asType === 'undefined') {
        as = url_1.format(href, { unicode: true });
    }
    else if (asType === 'string') {
        as = originalAs;
    }
    else {
        throw new Error(`'as' type must be 'string', but it is ${asType}`);
    }
    return as;
};
const parseHref = (originalHref) => {
    const hrefType = typeof originalHref;
    let href;
    if (hrefType === 'string') {
        href = url_1.parse(originalHref, true /* parseQueryString */);
    }
    else if (hrefType === 'object') {
        href = { ...originalHref };
        href.query = originalHref.query ? { ...originalHref.query } : {};
    }
    else {
        throw new Error(`'href' type must be either 'string' or 'object', but it is ${hrefType}`);
    }
    return href;
};
exports.lngPathCorrector = (config, currentRoute, currentLanguage) => {
    const { allLanguages, localeSubpaths } = config;
    const { as: originalAs, href: originalHref } = currentRoute;
    if (!allLanguages.includes(currentLanguage)) {
        throw new Error('Invalid configuration: Current language is not included in all languages array');
    }
    const href = parseHref(originalHref);
    let as = parseAs(originalAs, href);
    /*
    url.format prefers the 'url.search' string over
    the 'url.query' object, so remove the search
    string to ensure the query object is used.
  */
    delete href.search;
    /*
    Strip any/all subpaths from the `as` value
  */
    Object.values(localeSubpaths || {}).forEach((subpath) => {
        if (index_1.subpathIsPresent(as, subpath)) {
            as = index_1.removeSubpath(as, subpath);
        }
    });
    if (index_1.subpathIsRequired(config, currentLanguage)) {
        const basePath = `${href.protocol}//${href.host}`;
        const currentAs = as === null || as === void 0 ? void 0 : as.replace(basePath, '');
        const subpath = index_1.subpathFromLng(config, currentLanguage);
        as = `/${subpath}${currentAs}`.replace(/\/$/, '');
        href.query.lng = currentLanguage;
        href.query.subpath = subpath;
    }
    return { as, href };
};
