import {
  FieldQuery,
  FragmentDefinitions,
  getInlineFragment,
  ObjectValueWithVariables,
} from "../shared";

export default function getFieldQueryForPath(
  fragmentDefinitions: FragmentDefinitions<ObjectValueWithVariables>,
  query: FieldQuery<ObjectValueWithVariables> | null,
  path: string[]
): FieldQuery<ObjectValueWithVariables> | null {
  if (!query || path.length === 0) {
    return query;
  }
  if (path.length < 2) {
    throw new Error(`Invalid path provided: [${path.join(", ")}]`);
  }

  return getFieldQueryForPath(
    fragmentDefinitions,
    getInlineFragment(fragmentDefinitions, query[path[0]]).selection[path[1]]
      .fieldQuery,
    path.slice(2)
  );
}
