import { reactive } from "vue";
import { debugLog } from "@/helpers/debug-log-helper";

const queryStash = reactive({
    queries: [],
});

function stash(key, value) {
    const existingValue = getStashedQuery(key);

    if (existingValue) {
        existingValue.value = value;
        existingValue.used = false;
        return;
    }

    queryStash.queries.push({
        key: key,
        value: value,
        used: false,
    });
}

export function stashAllQueries(toRoute) {
    const keys = Object.keys(toRoute.query);

    keys.forEach((k) => stash(k, toRoute.query[k]));
}

function getStashedQuery(key) {
    debugLog(`Fetching querystring with key:`, key);
    const match = queryStash.queries.find(
        (entry) => entry?.key?.toLowerCase() === key?.toLowerCase()
    );

    if (match) {
        debugLog(`Found result:`, match.value);
        debugLog(`Already consumed:`, match.used);
    } else {
        debugLog(`Found no result`);
    }

    return match;
}

export function peekQueryFromStash(key) {
    return getStashedQuery(key)?.value;
}

export function consumeQueryFromStash(key) {
    const match = getStashedQuery(key);

    if (match) {
        if (!match.used) {
            match.used = true;
            return match.value;
        }

        return null;
    }

    return null;
}

export function clearStash() {
    queryStash.queries = [];
}
