type Changes = {
    path: string;
    oldValue: any;
    newValue: any;
};

function checkChanges(oldObject: any, newObject: any): Changes[] {
    const changes: Changes[] = [];

    // Helper function to recursively find changes
    function findChanges(oldValue: any, newValue: any, path: string = '') {
        if (oldValue !== newValue) {
            changes.push({ path, oldValue, newValue });
        } else if (Array.isArray(oldValue)) {
            if (oldValue.length !== newValue.length) {
                changes.push({ path, oldValue, newValue });
            } else {
                oldValue.forEach((item, index) => {
                    findChanges(item, newValue[index], `${path}[${index}]`);
                });
            }
        } else if (typeof oldValue === 'object' && oldValue !== null && newValue !== null) {
            Object.keys(newValue).forEach(key => {
                findChanges(oldValue[key], newValue[key], path ? `${path}.${key}` : key);
            });
        }
    }
    findChanges(oldObject, newObject);

    return changes;
}

function generateRevertObject(changes: Changes[]): any {
    const revertObject: any = {};

    changes.forEach(change => {
        let currentObj = revertObject;
        const keys = change.path.split('.');
        keys.forEach((key, index) => {
            if (index === keys.length - 1) {
                currentObj[key] = change.oldValue;
            } else {
                currentObj[key] = currentObj[key] || {};
                currentObj = currentObj[key];
            }
        });
    });

    return revertObject;
}

// Example usage:
const oldObject = {
    id: 1,
    content: "Old content",
    image: "old.jpg",
    subject_id: "math",
    isBase: false,
    tags: [{ name: "tag1", id: 1 }, { name: "tag2", id: 2 }]
};

const newObject = {
    id: 1,
    content: "New content",
    image: "new.jpg",
    subject_id: "science",
    isBase: true,
    tags: [{ name: "tag1", id: 1 }, { name: "tag3", id: 3 }]
};

const changes = checkChanges(oldObject, newObject);
console.log("Changes:", changes);

const revertObject = generateRevertObject(changes);
console.log("Revert Object:", revertObject);
