import { visit } from '@takeshape/util';
import isString from 'lodash/isString.js';
import last from 'lodash/last.js';
import set from 'lodash/set.js';
import unset from 'lodash/unset.js';
const TAKESHAPE_RESOLVERS = ['takeshape:getUser', 'takeshape:search', 'takeshape:queryApiIndex', 'util:wrap'];
function getServicePath(path) {
    const servicePath = [...path];
    servicePath.splice(-1, 1, 'service');
    return servicePath;
}
const migrate = async (_, projectSchema) => {
    visit(projectSchema, ['@ref', '@mapping', 'name'], (value, path) => {
        if (isString(value)) {
            const name = last(path);
            if (name === 'name' && value === 'debug:noop') {
                set(projectSchema, path, 'util:noop');
                unset(projectSchema, getServicePath(path));
            }
            else if (name === 'name' && value === 'util:wrap') {
                unset(projectSchema, getServicePath(path));
            }
            else if (name === 'name' && value.startsWith('takeshape:')) {
                const serviceName = TAKESHAPE_RESOLVERS.includes(value) ? 'takeshape' : 'shapedb';
                set(projectSchema, getServicePath(path), serviceName);
                set(projectSchema, path, value.replace('takeshape:', `${serviceName}:`));
            }
            else {
                set(projectSchema, path, value.replace('takeshape:local', 'shapedb'));
            }
        }
    });
    return {
        ...projectSchema,
        schemaVersion: '3.31.0'
    };
};
export default migrate;
