import { normalizeRefExpression } from "../../refs.js";
function migrateListQuery(listConfig) {
    const { pagination, name, ...restConfig } = listConfig;
    const result = { ...restConfig, query: name };
    if (pagination) {
        const { itemsToIndexPath, ...restPagination } = pagination;
        result.pagination = { ...restPagination, itemsPath: itemsToIndexPath };
    }
    return result;
}
function queriesToLoaders(queries) {
    if (queries.list) {
        const loaders = {
            list: Array.isArray(queries.list) ? queries.list.map(migrateListQuery) : migrateListQuery(queries.list)
        };
        if (queries.get) {
            const { name, ...restGet } = queries.get;
            loaders.get = { ...restGet, query: name };
        }
        return loaders;
    }
}
function migrateTrigger(trigger) {
    const { query, ...rest } = trigger;
    return { ...rest, loader: query };
}
const migrate = async (_, projectSchema) => {
    const updatedShapes = { ...projectSchema.shapes };
    const { indexedShapes, ...rest } = projectSchema;
    if (indexedShapes) {
        for (const [name, config] of Object.entries(indexedShapes)) {
            let shape = updatedShapes[name];
            shape ||= {
                name,
                id: name,
                title: name,
                schema: {
                    extends: [{ '@ref': normalizeRefExpression(projectSchema, name) }]
                }
            };
            const loaders = queriesToLoaders(config.queries);
            if (loaders) {
                shape.loaders = loaders;
            }
            shape.cache = {
                enabled: true,
                fragment: config.query,
                triggers: config.triggers.map(migrateTrigger)
            };
            updatedShapes[name] = shape;
        }
    }
    return {
        ...rest,
        shapes: updatedShapes,
        schemaVersion: '3.32.0'
    };
};
export default migrate;
