import { visit } from '@takeshape/util';
import isEmpty from 'lodash/isEmpty.js';
import omit from 'lodash/omit.js';
function omitOptions(resolver, names) {
    if (resolver.options) {
        const newOptions = omit(resolver.options, names);
        if (isEmpty(newOptions)) {
            resolver.options = undefined;
        }
        else {
            resolver.options = newOptions;
        }
    }
}
const migrate = async (_, projectSchema) => {
    /**
     * Resolver props that are guaranteed in this version, and dependent on the
     * resolver type. Ensure they exist.
     */
    const ensureResolverOptions = (resolver) => {
        if (resolver.name.startsWith('takeshape')) {
            if (!resolver.shapeName) {
                resolver.shapeName =
                    resolver.options?.model ?? resolver.options?.indexedShape ?? '';
                omitOptions(resolver, ['model', 'indexedShape']);
            }
        }
        if (resolver.name.startsWith('graphql')) {
            if (!resolver.fieldName) {
                resolver.fieldName = resolver.options?.fieldName ?? '';
                omitOptions(resolver, ['fieldName']);
            }
        }
        if (resolver.name.startsWith('awsLambda')) {
            if (!resolver.functionName) {
                resolver.functionName = resolver.options?.functionName ?? '';
                omitOptions(resolver, ['functionName']);
            }
        }
        if (resolver.name.startsWith('rest')) {
            if (!resolver.path) {
                if (resolver.pathParams) {
                    resolver.path = {
                        ...resolver.pathParams,
                        serialize: {
                            ...resolver.pathParams.serialize,
                            template: resolver.options?.path
                        }
                    };
                }
                else {
                    resolver.path = resolver.options?.path ?? '';
                }
                omitOptions(resolver, ['path']);
            }
        }
        /**
         * `resolver.name` was previously validated with app code and v3.9.0
         * enumerates the previous validation, making this assertion safe.
         */
        return resolver;
    };
    /**
     * Function will visit each resolver in the schema and mutate them.
     */
    visit(projectSchema, ['resolver', '@resolver'], (resolver) => {
        if (resolver.compose) {
            resolver.compose.forEach(ensureResolverOptions);
        }
        else {
            ensureResolverOptions(resolver);
        }
    });
    return {
        ...projectSchema,
        schemaVersion: '3.9.0'
    };
};
export default migrate;
