import { useQuery } from "@tanstack/react-query";
import { useAuth } from "@/contexts/AuthContext";
import { entitiesService } from "@/services/entities.service";

interface UsePermissionsReturn {
  permissions: string[];
  isLoading: boolean;
  hasPermission: (permission: string) => boolean;
  hasAnyPermission: (permissions: string[]) => boolean;
  hasAllPermissions: (permissions: string[]) => boolean;
  isAdmin: boolean;
  isDeveloper: boolean;
}

export function usePermissions(entityId?: number): UsePermissionsReturn {
  const { user } = useAuth();

  const activeEntityId = entityId ?? user?.entities?.[0]?.id;

  const { data: permissions = [], isLoading } = useQuery({
    queryKey: ["permissions", activeEntityId],
    queryFn: () => entitiesService.getPermissions(activeEntityId!),
    enabled: !!activeEntityId && !!user,
    staleTime: 10 * 60 * 1000,
  });

  const isAdmin = user?.user_type === "admin" || user?.user_type === "developer";
  const isDeveloper = user?.user_type === "developer";

  const hasPermission = (permission: string): boolean => {
    if (isAdmin) return true;
    return permissions.includes(permission);
  };

  const hasAnyPermission = (perms: string[]): boolean => {
    if (isAdmin) return true;
    return perms.some((p) => permissions.includes(p));
  };

  const hasAllPermissions = (perms: string[]): boolean => {
    if (isAdmin) return true;
    return perms.every((p) => permissions.includes(p));
  };

  return {
    permissions,
    isLoading,
    hasPermission,
    hasAnyPermission,
    hasAllPermissions,
    isAdmin,
    isDeveloper,
  };
}
