'use client';

import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useAuthStore } from '@/lib/auth-store';

interface Props {
  permission?: string;
  children: React.ReactNode;
}

/**
 * Wraps a page to enforce auth + optional permission check.
 * - Not logged in → redirect to /login
 * - Missing permission → redirect to /dashboard
 */
export function PermissionGuard({ permission, children }: Props) {
  const router = useRouter();
  const isAuthenticated = useAuthStore((s) => s.isAuthenticated);
  const hasPermission = useAuthStore((s) => s.hasPermission);

  useEffect(() => {
    if (!isAuthenticated) {
      router.replace('/login');
      return;
    }
    if (permission && !hasPermission(permission)) {
      router.replace('/dashboard');
    }
  }, [isAuthenticated, permission, hasPermission, router]);

  if (!isAuthenticated) return null;
  if (permission && !hasPermission(permission)) return null;

  return <>{children}</>;
}
