/**
 * Hook for capabilities (static version)
 * system_capabilities table has been removed, using static config
 */

import { useEffect, useRef, useState } from 'react';
import { getCapabilities } from '@/utils/capabilitiesSync';
import { useAuth } from '@/contexts/AuthContext';
import { isAdminUser } from '@/utils/adminCheck';

export function useCapabilitiesSync() {
  const { user } = useAuth();
  const hasLogged = useRef(false);
  const [isAdmin, setIsAdmin] = useState(false);

  useEffect(() => {
    if (!user) { setIsAdmin(false); return; }
    let cancelled = false;
    isAdminUser(user.id).then((ok) => { if (!cancelled) setIsAdmin(ok); });
    return () => { cancelled = true; };
  }, [user]);

  useEffect(() => {
    // Log once per session for debugging
    if (!user || !isAdmin || hasLogged.current) {
      return;
    }

    console.log('Capabilities loaded from static config:', Object.keys(getCapabilities().pageActions).length, 'page actions,', Object.keys(getCapabilities().dataActions).length, 'data actions');
    hasLogged.current = true;
  }, [user, isAdmin]);
}

// Manual sync function - now just returns static config info
export async function manualSyncCapabilities(): Promise<{ success: boolean; message: string }> {
  const caps = getCapabilities();
  const pageCount = Object.keys(caps.pageActions).length;
  const dataCount = Object.keys(caps.dataActions).length;
  return { 
    success: true, 
    message: `静态配置已加载: ${pageCount} 个页面操作, ${dataCount} 个数据操作` 
  };
}
