import omit from 'lodash/omit.js';
function hasWebhook(projectSchema, config) {
    const queryName = config.queries?.single?.name;
    if (!queryName) {
        return false;
    }
    const resolver = projectSchema?.queries[queryName]?.resolver;
    return resolver && 'service' in resolver && projectSchema?.services?.[resolver.service].provider === 'shopify';
}
const migrate = async (_, { indexedShapes: oldIndexedShapes, ...projectSchema }) => {
    if (!oldIndexedShapes) {
        return {
            ...projectSchema,
            schemaVersion: '3.12.3'
        };
    }
    const indexedShapes = Object.fromEntries(Object.entries(oldIndexedShapes).map(([shapeName, config]) => {
        const queries = {};
        const triggers = [];
        if (!config.queries) {
            return [
                shapeName,
                {
                    ...config,
                    queries,
                    triggers
                }
            ];
        }
        if (hasWebhook(projectSchema, config)) {
            queries.get = config.queries.single;
            triggers.push({
                type: 'webhook',
                query: 'get',
                service: 'shopify',
                events: ['products/create', 'products/update', 'products/delete']
            });
        }
        const oldPagination = config.queries.all?.pagination;
        const pagination = oldPagination === undefined
            ? undefined
            : oldPagination.type === 'cursor'
                ? {
                    ...oldPagination,
                    itemsToIndexPath: oldPagination.itemsPath,
                    pageSize: oldPagination.size,
                    pageSizeArg: oldPagination.sizeArg
                }
                : oldPagination.type === 'offset'
                    ? {
                        ...oldPagination,
                        itemsToIndexPath: oldPagination.itemsPath,
                        itemTotalPath: oldPagination.totalPath,
                        offsetArg: oldPagination.offsetParam
                    }
                    : {
                        ...oldPagination,
                        itemsToIndexPath: oldPagination.itemsPath,
                        pageTotalPath: oldPagination.totalPagesPath
                    };
        queries.list = pagination
            ? {
                ...omit(config.queries.all, 'interval'),
                pagination
            }
            : omit(config.queries.all, 'interval', 'pagination');
        triggers.push({
            type: 'schedule',
            query: 'list',
            interval: config.queries.all.interval ?? 60 * 24
        });
        return [
            shapeName,
            {
                ...config,
                queries,
                triggers
            }
        ];
    }));
    return {
        ...projectSchema,
        schemaVersion: '3.12.3',
        indexedShapes
    };
};
export default migrate;
