import { isDefined, visit } from '@takeshape/util';
import get from 'lodash/get.js';
import omit from 'lodash/omit.js';
import set from 'lodash/set.js';
const migrate = async (_, projectSchema) => {
    visit(projectSchema, ['@relationship'], (relationship, path) => {
        const propertyPath = path.slice(0, -1);
        const originalPropertySchema = get(projectSchema, propertyPath);
        const propertySchema = omit(originalPropertySchema, ['@relationship', 'type', '$ref']);
        const shapeIdMap = new Map(Object.values(projectSchema.shapes).map((shape) => [shape.id, shape]));
        const shapeIdsToShapeRefs = (shapeIds) => {
            return shapeIds
                .map((shapeId) => {
                let shape;
                if (shapeId === 'ASSET') {
                    shape = { name: 'Asset' };
                }
                else {
                    shape = shapeIdMap.get(shapeId);
                }
                if (!shape) {
                    return;
                }
                return {
                    '@ref': `local:${shape.name}`
                };
            })
                .filter(isDefined);
        };
        const shapeRefs = shapeIdsToShapeRefs(relationship.shapeIds);
        const shapeRefsSchema = shapeRefs.length === 1 ? shapeRefs[0] : { oneOf: shapeRefs };
        if (relationship.type === 'multiple') {
            propertySchema.type = 'array';
            propertySchema.items = shapeRefsSchema;
            propertySchema['@input'] = {
                type: 'array',
                items: {
                    '@ref': 'local:TSRelationship'
                }
            };
        }
        else {
            propertySchema.type = undefined;
            Object.assign(propertySchema, shapeRefsSchema);
            propertySchema['@input'] = {
                '@ref': 'local:TSRelationship'
            };
        }
        propertySchema['@args'] = 'TSRelationshipArgs';
        propertySchema['@resolver'] = {
            name: 'takeshape:getRelated',
            service: 'takeshape:local',
            options: {
                nullable: true
            }
        };
        set(projectSchema, propertyPath, propertySchema);
    });
    return {
        ...projectSchema,
        schemaVersion: '3.18.0'
    };
};
export default migrate;
