"use strict";
/**
 * Migration: Wrap TinyDataStore/TinyStorage constructor arguments in initialValue
 *
 * Transforms constructor calls to wrap the argument in an { initialValue: ... } object.
 * Skips instances that already have an initialValue property.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = update;
const devkit_1 = require("@nx/devkit");
const ts_morph_1 = require("ts-morph");
const TARGET_CLASSES = ['TinyDataStore', 'TinyStorage'];
async function update(tree) {
    devkit_1.logger.info('🔄 Wrapping TinyDataStore/TinyStorage constructor arguments in initialValue...');
    const project = new ts_morph_1.Project({
        manipulationSettings: { quoteKind: ts_morph_1.QuoteKind.Single },
    });
    let updatedCount = 0;
    (0, devkit_1.visitNotIgnoredFiles)(tree, '.', (filePath) => {
        if (!filePath.endsWith('.ts') && !filePath.endsWith('.tsx'))
            return;
        if (!filePath.includes('unisphere/'))
            return;
        const content = tree.read(filePath, 'utf-8');
        if (!content)
            return;
        if (!TARGET_CLASSES.some((cls) => content.includes(cls)))
            return;
        const sourceFile = project.createSourceFile(filePath, content, {
            overwrite: true,
        });
        let hasChanges = false;
        const newExpressions = sourceFile.getDescendantsOfKind(ts_morph_1.SyntaxKind.NewExpression);
        for (const expr of newExpressions) {
            const exprText = expr.getExpression().getText();
            if (!TARGET_CLASSES.includes(exprText))
                continue;
            const args = expr.getArguments();
            if (args.length !== 1)
                continue;
            const arg = args[0];
            // Skip if argument already has an initialValue property
            if (arg.getKind() === ts_morph_1.SyntaxKind.ObjectLiteralExpression) {
                const objLiteral = arg.asKind(ts_morph_1.SyntaxKind.ObjectLiteralExpression);
                if (objLiteral?.getProperty('initialValue'))
                    continue;
            }
            const argText = arg.getText();
            arg.replaceWithText(`{\n      initialValue: ${argText},\n    }`);
            hasChanges = true;
        }
        if (hasChanges) {
            tree.write(filePath, sourceFile.getFullText());
            updatedCount++;
            devkit_1.logger.info(`  ✅ Updated ${filePath}`);
        }
    });
    if (updatedCount === 0) {
        devkit_1.logger.info('ℹ️ No TinyDataStore/TinyStorage instances needed transformation');
    }
    else {
        await (0, devkit_1.formatFiles)(tree);
        devkit_1.logger.info(`✅ Wrapped constructor arguments in initialValue for ${updatedCount} file(s)`);
    }
}
