import { getRef, refItemToShape, refItemToShapeSchema } from "../refs.js";
import { isArraySchema, isObjectSchema, isRefSchema } from "../types/index.js";
/**
 *
 * @param projectSchema
 * @param schema
 * @param queryPath
 *
 * @example
 * findShapeAtPath(projectSchema, projectSchema.shapes.Shopify_ProductConnection.shape, ['edges', 'node']) // finds {'@ref': Shopify_Product}
 */
export function findSchemaAtPath(projectSchema, schema, queryPath) {
    if (queryPath.length === 0) {
        return schema;
    }
    const [prop, ...rest] = queryPath;
    if (isRefSchema(schema)) {
        const ref = getRef(projectSchema, schema);
        if (ref) {
            const shapeSchema = refItemToShapeSchema(projectSchema, ref);
            if (shapeSchema) {
                return findSchemaAtPath(projectSchema, shapeSchema, queryPath);
            }
        }
        return undefined;
    }
    if (isArraySchema(schema)) {
        return findSchemaAtPath(projectSchema, schema.items, queryPath);
    }
    if (isObjectSchema(schema)) {
        const propSchema = schema.properties[prop];
        if (propSchema) {
            return findSchemaAtPath(projectSchema, propSchema, rest);
        }
    }
    return undefined;
}
/**
 *
 * @param projectSchema
 * @param propSchema
 * @param queryPath
 *
 * @example
 * findShapeAtPath(projectSchema, projectSchema.shapes.Shopify_ProductConnection.shape, ['edges', 'node']) // finds Shopify_Product
 */
export function findShapeAtPath(projectSchema, propSchema, queryPath) {
    const result = findSchemaAtPath(projectSchema, propSchema, queryPath);
    if (result) {
        const refItem = getRef(projectSchema, result.items ?? result);
        return refItem && refItemToShape(projectSchema, refItem);
    }
}
