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

export const useHakAkses = () => {
    const { user, checkAuth } = useAuth();
    
    /**
     * Get all pages that user has access to based on their roles
     */
    const getAllowedPages = async (): Promise<string[]> => {
        // Ensure user is loaded
        if (!user.value) {
            await checkAuth();
        }
        
        const currentUser = user.value;
        
        if (!currentUser) {
            return [];
        }

        // Get roles and groups from multiple possible sources in User object
        const roles = [
            ...(currentUser.roles || []),
            ...((currentUser as any).realm_access?.roles || []),
            ...((currentUser as any).resource_access?.['web-antrean']?.roles || [])
        ];
        
        const groups = (currentUser as any).groups || [];
        
        // Combine everything the user belongs to: Roles, Groups, and their own Username
        const entities = [...new Set([
            (currentUser as any).namaUser, // Individual user mapping support
            ...roles, 
            ...groups
        ])].filter(Boolean);
        
        if (entities.length === 0) {
            return [];
        }

        try {
            const headers = import.meta.server ? useRequestHeaders(['cookie']) as Record<string, string> : {}
            // Fetch all hak akses data
            const response = await $fetch<{ success: boolean, data: HakAkses[] }>('/api/hak-akses', { headers });
            
            if (response && response.success && Array.isArray(response.data)) {
                const hakAksesList = response.data;
                
                // Filter hak akses that match user's entities and are active
                const userHakAkses = hakAksesList.filter((hakAkses) => 
                    entities.includes(hakAkses.namaHakAkses) && 
                    hakAkses.status === 'aktif'
                );
                
                // Combine all pages from all matching hak akses
                const allPages = userHakAkses.reduce((pages: string[], hakAkses) => {
                    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));
    };
    
    const allHakAksesData = ref<HakAkses[]>([]);
    const isLoading = ref(false);

    const fetchHakAkses = async () => {
        isLoading.value = true;
        try {
            const headers = import.meta.server ? useRequestHeaders(['cookie']) as Record<string, string> : {}
            const response = await $fetch<{ success: boolean, data: HakAkses[] }>('/api/hak-akses', { headers });
            if (response && response.success) {
                allHakAksesData.value = response.data;
            }
        } catch (error) {
            console.error('Error fetching hak akses:', error);
        } finally {
            isLoading.value = false;
        }
    };

    return {
        allHakAksesData,
        isLoading,
        fetchHakAkses,
        getAllowedPages,
        hasPageAccess,
        hasAnyPageAccess
    };
};
