export function returnToFromPageUrl(pageUrl: string): string {
    const queryStart = pageUrl.indexOf('?');

    if (queryStart === -1) {
        return '';
    }

    const hashStart = pageUrl.indexOf('#', queryStart);
    const query = pageUrl.slice(
        queryStart + 1,
        hashStart === -1 ? undefined : hashStart,
    );

    return new URLSearchParams(query).get('return_to') ?? '';
}

export function withReturnTo(href: string, returnTo: string): string {
    const hashStart = href.indexOf('#');
    const base = hashStart === -1 ? href : href.slice(0, hashStart);
    const hash = hashStart === -1 ? '' : href.slice(hashStart);
    const queryStart = base.indexOf('?');
    const path = queryStart === -1 ? base : base.slice(0, queryStart);
    const query = queryStart === -1 ? '' : base.slice(queryStart + 1);
    const params = new URLSearchParams(query);

    params.set('return_to', returnTo);

    return `${path}?${params.toString()}${hash}`;
}
