/**
 * Dynamic Ziggy loader
 *
 * Memuat route yang sesuai berdasarkan user role.
 * - User biasa: hanya lihat route frontend
 * - Admin: lihat route admin + frontend
 */

// Type untuk Ziggy config
interface ZiggyConfig {
    url: string;
    port: number | null;
    defaults: Record<string, unknown>;
    routes: Record<
        string,
        {
            uri: string;
            methods: string[];
            parameters?: string[];
        }
    >;
}

// Singleton untuk menyimpan Ziggy config
let ziggyConfig: ZiggyConfig | null = null;
let loadPromise: Promise<ZiggyConfig> | null = null;

/**
 * Detect if current user is admin based on URL path
 */
function isAdminRoute(): boolean {
    return typeof window !== 'undefined' && window.location.pathname.startsWith('/admin');
}

/**
 * Load appropriate Ziggy config based on user role
 */
async function loadZiggyConfig(): Promise<ZiggyConfig> {
    if (ziggyConfig) return ziggyConfig;
    if (loadPromise) return loadPromise;

    loadPromise = (async () => {
        try {
            // Dynamic import based on route
            if (isAdminRoute()) {
                // Admin users get all routes (frontend + admin)
                const adminMod = (await import('./ziggy-admin.js')) as any;
                ziggyConfig = adminMod.Ziggy;
            } else {
                // Regular users only get frontend routes
                const frontendMod = (await import('./ziggy-frontend.js')) as any;
                ziggyConfig = frontendMod.Ziggy;
            }
            return ziggyConfig!;
        } catch (error) {
            console.error('Failed to load Ziggy config:', error);
            // Fallback: try loading default ziggy.js
            const fallbackMod = (await import('./ziggy.js')) as any;
            ziggyConfig = fallbackMod.Ziggy;
            return ziggyConfig!;
        } finally {
            // no-op
        }
    })();

    return loadPromise;
}

/**
 * Get current Ziggy config (synchronous, returns null if not loaded)
 */
export function getZiggyConfig(): ZiggyConfig | null {
    return ziggyConfig;
}

/**
 * Initialize Ziggy config
 * Call this early in app initialization
 */
export async function initializeZiggy(): Promise<void> {
    await loadZiggyConfig();
}

/**
 * Merge Ziggy config with window.Ziggy if available
 * (for server-side injected routes via @routes directive)
 */
export function mergeWindowZiggy(): void {
    if (typeof window !== 'undefined' && (window as any).Ziggy && ziggyConfig) {
        Object.assign(ziggyConfig.routes, (window as any).Ziggy.routes);
    }
}

// Re-export types for convenience
export type { ZiggyConfig };
