"use strict";
/**
 * Migration: Fix vite.config.ts cache directory paths
 *
 * This migration ensures that vite.config.ts cache directory paths
 * match the package name. This fixes any packages that were renamed
 * before the rename-package generator was updated to handle vite configs.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = update;
const devkit_1 = require("@nx/devkit");
async function update(tree) {
    devkit_1.logger.info('');
    devkit_1.logger.info('🔄 Fixing vite.config.ts cache directory paths...');
    devkit_1.logger.info('');
    if (!tree.exists('.unisphere')) {
        devkit_1.logger.info('No .unisphere file found, skipping migration');
        return;
    }
    const unisphereConfig = (0, devkit_1.readJson)(tree, '.unisphere');
    const packagesConfig = unisphereConfig.elements?.packages || {};
    let updatedCount = 0;
    for (const [packageName, config] of Object.entries(packagesConfig)) {
        const sourceRoot = config.sourceRoot;
        if (!sourceRoot) {
            continue;
        }
        const viteConfigPath = `${sourceRoot}/vite.config.ts`;
        if (!tree.exists(viteConfigPath)) {
            continue;
        }
        let content = tree.read(viteConfigPath, 'utf-8');
        if (!content) {
            continue;
        }
        // Check if vite config has cache paths that don't match the package name
        const expectedPattern = `package-${packageName}`;
        // Match any package-{name} pattern in cache paths
        const cachePathRegex = /package-([a-z0-9-]+)/g;
        const matches = content.match(cachePathRegex);
        if (matches) {
            let needsUpdate = false;
            for (const match of matches) {
                if (match !== expectedPattern) {
                    needsUpdate = true;
                    break;
                }
            }
            if (needsUpdate) {
                // Replace all package-{oldName} with package-{packageName}
                content = content.replace(cachePathRegex, expectedPattern);
                tree.write(viteConfigPath, content);
                devkit_1.logger.info(`✅ Fixed vite.config.ts for package "${packageName}"`);
                updatedCount++;
            }
        }
    }
    if (updatedCount === 0) {
        devkit_1.logger.info('All vite.config.ts files have correct cache paths');
    }
    else {
        devkit_1.logger.info('');
        devkit_1.logger.info(`✅ Fixed ${updatedCount} vite.config.ts file(s)`);
    }
    devkit_1.logger.info('');
}
