// composables/useHakAkses.ts
// Composable for handling user permissions/access based on hakAkses
import { useAuth } from "~/composables/useAuth";

export const useHakAkses = () => {
    const {user, checkAuth} = useAuth();
    
    /**
     * Get all pages that user has access to based on their roles
     */
    const getAllowedPages = async (): Promise<string[]> => {
        // Pastikan user sudah ter-load dari cookie/session
        // Jika user.value masih null, panggil checkAuth() untuk load dari API session
        if (!user.value) {
            console.log('🔄 User belum ter-load, memanggil checkAuth()...');
            await checkAuth();
        }
        
        const currentUser = user.value;
        console.log('Current User in getAllowedPages:', currentUser);
        
        if (!currentUser || !currentUser.roles || currentUser.roles.length === 0) {
            console.log('⚠️ User tidak memiliki roles');
            return [];
        }

        
        try {
            // Fetch all hak akses data
            const response = await $fetch('/api/hak-akses');
            
            if (response && typeof response === 'object' && 'success' in response && response.success && 'data' in response) {
                const hakAksesList = Array.isArray(response.data) ? response.data : [];
                
                // Filter hak akses that match user's roles and are active
                const userHakAkses = hakAksesList.filter((hakAkses: any) => 
                    currentUser.roles?.includes(hakAkses.namaHakAkses) && 
                    hakAkses.status === 'aktif'
                );
                
                // Combine all pages from all matching hak akses
                const allPages = userHakAkses.reduce((pages: string[], hakAkses: any) => {
                    if (hakAkses.pages && Array.isArray(hakAkses.pages)) {
                        return [...pages, ...hakAkses.pages];
                    }
                    return pages;
                }, []);
                
                // Remove duplicates
                return [...new Set(allPages)];
            }
            
            return [];
        } catch (error) {
            console.error('Error fetching allowed pages:', error);
            return [];
        }
    };
    
    /**
     * Check if user has access to a specific page
     */
    const hasPageAccess = async (pagePath: string): Promise<boolean> => {
        const allowedPages = await getAllowedPages();
        return allowedPages.includes(pagePath);
    };
    
    /**
     * Check if user has access to any page in a list
     */
    const hasAnyPageAccess = async (pagePaths: string[]): Promise<boolean> => {
        const allowedPages = await getAllowedPages();
        return pagePaths.some(path => allowedPages.includes(path));
    };
    
    return {
        getAllowedPages,
        hasPageAccess,
        hasAnyPageAccess
    };
};
