// resources/js/stores/prefetch.js
import { defineStore } from 'pinia';
import { ref, watch } from 'vue';

const CACHE_KEY = 'bukid_prefetch_cache';
const SIX_MONTH_MS = 6 * 30 * 24 * 60 * 60 * 1000;

export const usePrefetchStore = defineStore('prefetch', () => {
    // Load initial state from localStorage
    const saved = localStorage.getItem(CACHE_KEY);
    const caches = ref(saved ? JSON.parse(saved) : {});

    // Save to localStorage whenever caches changes
    watch(caches, (newCaches) => {
        localStorage.setItem(CACHE_KEY, JSON.stringify(newCaches));
    }, { deep: true });

    const setCache = (key, data) => {
        caches.value[key] = {
            data,
            timestamp: Date.now()
        };
    };

    const getCache = (key) => {
        const entry = caches.value[key];
        if (!entry) return null;

        // Check if within 6-month validity window
        if (Date.now() - entry.timestamp > SIX_MONTH_MS) {
            delete caches.value[key];
            return null;
        }

        return entry.data;
    };

    const hasCache = (key) => {
        const entry = caches.value[key];
        if (!entry) return false;
        if (Date.now() - entry.timestamp > SIX_MONTH_MS) {
            delete caches.value[key];
            return false;
        }
        return true;
    };

    const clearCache = () => {
        caches.value = {};
    };

    return {
        caches,
        setCache,
        getCache,
        hasCache,
        clearCache
    };
});
