"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs = __importStar(require("fs"));
const path_1 = __importDefault(require("path"));
const child_process_1 = require("child_process");
const semver_1 = __importDefault(require("semver"));
const prompts_1 = require("@inquirer/prompts");
const rootDir = path_1.default.resolve(process.cwd());
function checkVersion(pkg) {
    return __awaiter(this, void 0, void 0, function* () {
        const packageName = '@akinon/next';
        const registryUrl = `https://registry.npmjs.org/${packageName}`;
        try {
            const response = yield fetch(registryUrl);
            const pkgInfo = (yield response.json());
            const latestVersion = pkgInfo['dist-tags'].latest;
            if (!semver_1.default.satisfies(pkg.dependencies['@akinon/next'], latestVersion)) {
                console.warn(`\x1b[43m Warning: The "${packageName}" package is currently at`, `\x1b[41m version ${pkg.dependencies['@akinon/next']}`, `\x1b[43m Please upgrade it to the latest version (${latestVersion}) to ensure plugin compatibility.`, '\x1b[0m\n');
            }
            else {
                console.log(`\x1b[42m Info: The package "${packageName}" is currently in the current version (${latestVersion}).`, '\x1b[0m\n');
            }
        }
        catch (error) {
            console.error(`\x1b[41mError: ${error === null || error === void 0 ? void 0 : error.message}`, '\x1b[0m\n');
        }
    });
}
exports.default = () => __awaiter(void 0, void 0, void 0, function* () {
    function findPluginsFilePath() {
        const option1 = path_1.default.resolve(rootDir, './src/plugins.js');
        const option2 = path_1.default.resolve(rootDir, './packages/akinon-next/plugins.js');
        if (fs.existsSync(option1)) {
            return option1;
        }
        else if (fs.existsSync(option2)) {
            return option2;
        }
        else {
            throw new Error('plugins.js was not found in either of the expected locations.');
        }
    }
    function findPackageJson() {
        const packageJsonPaths = [
            path_1.default.resolve(rootDir, './package.json'),
            path_1.default.resolve(rootDir, './apps/projectzeronext/package.json')
        ];
        for (const packageJsonPath of packageJsonPaths) {
            try {
                const pkg = require(packageJsonPath);
                if (pkg.dependencies['@akinon/next']) {
                    return pkg;
                }
            }
            catch (error) {
                continue;
            }
        }
        throw new Error('Could not find package.json with @akinon/next dependency');
    }
    const pkg = findPackageJson();
    yield checkVersion(pkg);
    const pluginsFilePath = findPluginsFilePath();
    let installedPlugins = [];
    try {
        installedPlugins = require(pluginsFilePath);
    }
    catch (error) {
        console.error('Error loading installed plugins:', error);
        process.exit(1);
    }
    const definedPlugins = [
        {
            name: 'Akifast',
            value: 'pz-akifast'
        },
        {
            name: 'Apple Pay',
            value: 'pz-apple-pay'
        },
        {
            name: 'B2B',
            value: 'pz-b2b'
        },
        {
            name: 'Basket Gift Pack',
            value: 'pz-basket-gift-pack'
        },
        {
            name: 'BKM Express',
            value: 'pz-bkm'
        },
        {
            name: 'Checkout Gift Pack',
            value: 'pz-checkout-gift-pack'
        },
        {
            name: 'Click & Collect',
            value: 'pz-click-collect'
        },
        {
            name: 'Credit Payment',
            value: 'pz-credit-payment'
        },
        {
            name: 'Garanti Pay',
            value: 'pz-gpay'
        },
        {
            name: 'Masterpass',
            value: 'pz-masterpass'
        },
        {
            name: 'Multi Basket',
            value: 'pz-multi-basket'
        },
        {
            name: 'One Click Checkout',
            value: 'pz-one-click-checkout'
        },
        {
            name: 'Otp',
            value: 'pz-otp'
        },
        {
            name: 'Pay On Delivery',
            value: 'pz-pay-on-delivery'
        },
        {
            name: 'Saved Card',
            value: 'pz-saved-card'
        },
        {
            name: 'Tabby Payment Extension',
            value: 'pz-tabby-extension'
        },
        {
            name: 'Tamara Payment Extension',
            value: 'pz-tamara-extension'
        },
        {
            name: 'Hepsipay',
            value: 'pz-hepsipay'
        },
        {
            name: 'Flow Payment',
            value: 'pz-flow-payment'
        },
        {
            name: 'Virtual Try-On',
            value: 'pz-virtual-try-on'
        },
        {
            name: 'Masterpass Rest',
            value: 'pz-masterpass-rest'
        },
        {
            name: 'Similar Products',
            value: 'pz-similar-products'
        },
        {
            name: 'Haso Payment Gateway',
            value: 'pz-haso'
        },
        {
            name: 'Google Pay',
            value: 'pz-google-pay'
        }
    ];
    try {
        const answers = yield (0, prompts_1.checkbox)({
            message: 'Please check/uncheck plugins to install/uninstall.',
            choices: definedPlugins.map((plugin) => ({
                name: plugin.name,
                value: plugin.value,
                checked: installedPlugins.includes(plugin.value)
            }))
        });
        if (!answers.length) {
            console.log('\x1b[33m%s\x1b[0m', `\nUninstalling all plugins.`);
        }
        console.log('\x1b[36m%s\x1b[0m', `\nPlease wait...`);
        fs.writeFileSync(pluginsFilePath, `module.exports = ${JSON.stringify(answers)};\n`, {
            encoding: 'utf-8'
        });
        (0, child_process_1.execSync)('yarn install', { stdio: 'pipe' });
        console.log('\x1b[32m%s\x1b[0m', `\n✓ ${answers.length
            ? 'Installed selected plugins'
            : 'Uninstalled all plugins'}.\n`);
    }
    catch (error) {
        process.exit(1);
    }
});
