"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = update;
const devkit_1 = require("@nx/devkit");
const path_1 = require("path");
const removePatchList = ['@changesets+cli'];
const forcePatchVersions = {
    '@changesets/cli': '2.29.7'
};
async function update(tree) {
    devkit_1.logger.info('🔄 Creating patches');
    try {
        // Check @nx/rollup version
        if (Object.keys(forcePatchVersions).length !== 0) {
            devkit_1.logger.info('removing patches of older versions');
            const pkg = (0, devkit_1.readJson)(tree, 'package.json');
            Object.keys(forcePatchVersions).forEach(key => {
                const version = pkg.devDependencies?.[key] || pkg.dependencies?.[key];
                if (version !== forcePatchVersions[key]) {
                    devkit_1.logger.error(`❌ ${key} version must be exactly ${forcePatchVersions[key]}`);
                    throw new Error(`${key} version must be exactly ${forcePatchVersions[key]}. did you migrate nx to other version?`);
                }
            });
        }
        // Create patches
        const patchesPath = 'patches';
        const patchesTemplatePath = (0, path_1.join)(__dirname, 'patches');
        // Delete existing patches folder content if it exists
        if (tree.exists(patchesPath)) {
            const existingFiles = tree.children(patchesPath);
            for (const file of existingFiles) {
                if (removePatchList.some(patch => file.includes(patch))) {
                    devkit_1.logger.info(`🗑️ Removing existing patch: ${file}`);
                    tree.delete((0, path_1.join)(patchesPath, file));
                }
                else {
                    devkit_1.logger.info(`✅ Patch: ${file} is up to date`);
                }
            }
            devkit_1.logger.info(`🧹 Cleaned up existing patches folder`);
        }
        // Copy all patch files using generateFiles
        (0, devkit_1.generateFiles)(tree, patchesTemplatePath, `./${patchesPath}`, {});
        // Log created patches
        const createdPatches = tree.children(patchesPath);
        for (const patchFile of createdPatches) {
            devkit_1.logger.info(`✅ Created patch: ${patchFile}`);
        }
        // Always log that patches were created
        devkit_1.logger.info(`✅ All patches created successfully`);
    }
    catch (error) {
        devkit_1.logger.error(`❌ Failed to create patches: ${error?.message || 'Unknown error'}`);
        throw error;
    }
}
