// resources/js/composables/useHashKeyCache.js
import { ref } from 'vue';

const hashDataStore = ref({});

/**
 * Composable for handling hashkey-based URL patterns and data caching.
 * Supported Patterns:
 * 1. /path--h:HASHKEY  -> Fetch data associated with the hashkey
 * 2. /path--e:PAYLOAD  -> Direct base64-encoded JSON payload in URL
 */
export function useHashKeyCache() {
    /**
     * Get data associated with a hashkey.
     * @param {string} key 
     * @returns {any|null}
     */
    const getHashData = (key) => {
        return hashDataStore.value[key] || null;
    };

    /**
     * Cache data against a hashkey.
     * @param {string} key 
     * @param {any} data 
     */
    const setHashData = (key, data) => {
        if (key && data) {
            hashDataStore.value[key] = data;
        }
    };

    /**
     * Decodes a base64 encoded payload from the URL.
     * @param {string} base64Payload 
     * @returns {any|null}
     */
    const decodePayload = (base64Payload) => {
        try {
            const decodedStr = atob(base64Payload);
            return JSON.parse(decodedStr);
        } catch (e) {
            console.error('[HashCache] Failed to decode URL payload:', e);
            return null;
        }
    };

    /**
     * Parse the current URL or a given URL for hashkey/payload patterns.
     * @param {string} urlString 
     * @returns {{type: 'hash'|'payload'|'none', value: any}}
     */
    const parseHashUrl = (urlString = window.location.pathname) => {
        const hashMatch = urlString.match(/--h:([A-Za-z0-9_-]+)/);
        if (hashMatch) {
            const hashkey = hashMatch[1];
            return { type: 'hash', value: hashkey, data: getHashData(hashkey) };
        }

        const payloadMatch = urlString.match(/--e:([A-Za-z0-9+/=_-]+)/);
        if (payloadMatch) {
            const payload = decodePayload(payloadMatch[1]);
            return { type: 'payload', value: payloadMatch[1], data: payload };
        }

        return { type: 'none', value: null, data: null };
    };

    /**
     * Formats a URL with a hashkey.
     * @param {string} baseUrl 
     * @param {string} hash 
     * @returns {string}
     */
    const formatHashUrl = (baseUrl, hash) => {
        return `${baseUrl.replace(/\/+$/, '')}--h:${hash}`;
    };

    /**
     * Formats a URL with an encoded payload.
     * @param {string} baseUrl 
     * @param {any} data 
     * @returns {string}
     */
    const formatPayloadUrl = (baseUrl, data) => {
        const payload = btoa(JSON.stringify(data));
        return `${baseUrl.replace(/\/+$/, '')}--e:${payload}`;
    };

    return {
        getHashData,
        setHashData,
        parseHashUrl,
        formatHashUrl,
        formatPayloadUrl,
        hashDataStore
    };
}
