import { useQuery } from '@tanstack/react-query';

import { getScopeChildren } from '@/shared/api/scope';
import type { TenantChild } from '@/shared/types/scope';

export interface TenantParent {
  readonly level: string;
  readonly id: string;
}

interface UseTenantChildrenOptions {
  readonly enabled?: boolean;
  readonly limit?: number;
}

/**
 * Lists the child tenants below `parent` (or below the user's own tenant when
 * `parent` is null) for the tenant switcher / drill-down cards.
 */
export function useTenantChildren(
  parent?: TenantParent | null,
  options?: UseTenantChildrenOptions,
) {
  return useQuery<{ rows: TenantChild[] }>({
    queryKey: ['scope-children', parent?.level ?? 'self', parent?.id ?? 'self', options?.limit ?? null],
    queryFn: () => getScopeChildren(parent?.level, parent?.id, { limit: options?.limit }),
    enabled: options?.enabled ?? true,
    retry: false,
  });
}
