import { stringify } from 'qs';
import { useNavigate, useSearchParams } from 'react-router-dom';

export const loginPath = '/login';

export const toLoginPage = () => {
    const { search, pathname } = window.location;
    const urlParams = new URL(window.location.href).searchParams;
    const redirect = urlParams.get('redirect');
    if (window.location.pathname !== loginPath && !redirect) {
        window.location.href =
            loginPath +
            '?' +
            stringify({
                redirect: pathname + search,
            });
    }
};

export const useSmartRouter = () => {
    const navigate = useNavigate();
    const [searchParams] = useSearchParams();

    const smartNavigate = (path: string, params?: Record<string, any>) => {
        const currentParams = new URLSearchParams(searchParams);
        if (params) {
            Object.entries(params).forEach(([key, value]) => {
                currentParams.set(key, value);
            });
        }
        const queryString = currentParams.toString();
        navigate(`${path}${queryString ? `?${queryString}` : ''}`);
    };

    return smartNavigate;
};
