// resources/js/composables/Core/usePrefetch.js
import { useNavigate } from './useNavigate';
import { useAuth } from './useAuth';
import axios from 'axios';
import { usePrefetchStore } from '../../stores/prefetch';

export function usePrefetch() {
    const { prefetch: prefetchJS } = useNavigate();
    const { hasRole, UserTypes } = useAuth();
    const prefetchStore = usePrefetchStore();

    // Registry of pages and their corresponding data endpoints
    // Each entry: { page: string, dataUrls: Array<{ url: string, method: string, payload: object }>, roles: string[] }
    const registry = [
        {
            page: 'UserList',
            dataUrls: [
                { url: '/admin/users/list', method: 'GET' }
            ],
            roles: [UserTypes.ULTIMATE, UserTypes.SUPER_OPERATOR]
        },
        {
            page: 'ManageStoresAdmin',
            dataUrls: [{ url: '/Admin/Stores/List', method: 'POST' }],
            roles: [UserTypes.ULTIMATE, UserTypes.SUPER_OPERATOR]
        },
        {
            page: 'ListStores',
            dataUrls: [{ url: '/ListStores/List/data', method: 'POST' }],
            roles: 'all'
        },
        {
            page: 'ManageProductsAdmin',
            dataUrls: [{ url: '/Admin/Products/List', method: 'POST' }],
            roles: [UserTypes.ULTIMATE, UserTypes.SUPER_OPERATOR]
        },
        {
            page: 'ShipmentList',
            dataUrls: [{ url: '/Shipments/List', method: 'POST' }],
            roles: 'all'
        },
        {
            page: 'CooperativeList',
            dataUrls: [{ url: '/Cooperatives/List', method: 'POST' }],
            roles: 'all'
        },
        {
            page: 'VerificationDashboard',
            dataUrls: [{ url: '/Farmers/List', method: 'POST' }],
            roles: [UserTypes.ULTIMATE, UserTypes.SUPER_OPERATOR, UserTypes.OPERATOR]
        },
        {
            page: 'ListReports',
            dataUrls: [{ url: '/admin/accounting/reports', method: 'POST' }],
            roles: [UserTypes.ULTIMATE, UserTypes.SUPER_OPERATOR]
        }
    ];

    /**
     * Prefetch a single data endpoint and store it in the persistent cache.
     */
    const prefetchData = async ({ url, method = 'GET', payload = {} }) => {
        try {
            const cacheKey = `${method}:${url}:${JSON.stringify(payload)}`;
            
            // Standardizing the request
            let response;
            if (method.toUpperCase() === 'POST') {
                response = await axios.post(url, payload);
            } else {
                response = await axios.get(url, { params: payload });
            }

            if (response.data) {
                prefetchStore.setCache(cacheKey, response.data);
                console.log(`[Prefetch] Cached ${url}`);
            }
        } catch (error) {
            console.warn(`[Prefetch] Failed to prefetch data for ${url}:`, error);
        }
    };

    /**
     * Trigger prefetching for ALL allowed modules.
     * Staggered to avoid network congestion.
     */
    const prefetchEverything = async () => {
        const allowedModules = registry.filter(item => {
            if (item.roles === 'all') return true;
            return item.roles.some(role => hasRole(role));
        });

        console.log(`[Prefetch] Starting universal prefetch for ${allowedModules.length} modules.`);

        // Process in a queue with small delay to avoid hammering
        for (const module of allowedModules) {
            // 1. Prefetch JS Chunk
            prefetchJS(module.page);

            // 2. Prefetch Data Endpoints
            for (const dataInfo of module.dataUrls) {
                // Background fetch, don't wait for completion before starting next module
                prefetchData(dataInfo);
            }

            // Small break between modules
            await new Promise(r => setTimeout(r, 200)); 
        }
    };

    return {
        prefetchEverything,
        prefetchData
    };
}
