/**
 * Installer Controller
 * 
 * Handles the 4-step installer process:
 * 1. Requirements Check
 * 2. Configuration Form
 * 3. ENV Example Generation
 * 4. Finish
 * 
 * ⚠️ CONSTRAINT: Conceptual only - does NOT break existing functionality
 */

const fs = require('fs');
const path = require('path');
const envAnalyzer = require('../services/env-analyzer.service');
const envGenerator = require('../services/env-generator.service');
const verifyLicense = require('../../config/licenceChecker.config.js');

/**
 * Step 1: Requirements Check
 */
exports.requirementsCheck = async (req, res) => {
    try {
        const checks = {
            nodeVersion: {
                required: '>=14.0.0',
                current: process.version,
                status: 'pass'
            },
            npmAvailable: {
                status: 'checking'
            },
            filePermissions: {
                status: 'checking'
            },
            databaseConnection: {
                status: 'optional',
                message: 'Database connection is optional for installer'
            }
        };

        // Check NPM availability
        try {
            const { execSync } = require('child_process');
            const npmVersion = execSync('npm --version', { encoding: 'utf8' }).trim();
            checks.npmAvailable = {
                current: npmVersion,
                status: 'pass'
            };
        } catch (error) {
            checks.npmAvailable = {
                status: 'fail',
                message: 'NPM not found in PATH'
            };
        }

        // Check file write permissions
        try {
            const testFile = path.join(process.cwd(), 'storage', 'test-write.tmp');
            const storageDir = path.dirname(testFile);

            // Ensure storage directory exists
            if (!fs.existsSync(storageDir)) {
                fs.mkdirSync(storageDir, { recursive: true });
            }

            fs.writeFileSync(testFile, 'test');
            fs.unlinkSync(testFile);

            checks.filePermissions = {
                status: 'pass',
                message: 'Write permissions available'
            };
        } catch (error) {
            checks.filePermissions = {
                status: 'fail',
                message: 'Cannot write to storage directory'
            };
        }

        // Optional database connection test (non-blocking)
        try {
            const mongoose = require('mongoose');
            if (mongoose.connection.readyState === 1) {
                checks.databaseConnection = {
                    status: 'pass',
                    message: 'Database already connected'
                };
            } else {
                checks.databaseConnection = {
                    status: 'info',
                    message: 'Database not connected (this is fine for installer)'
                };
            }
        } catch (error) {
            checks.databaseConnection = {
                status: 'info',
                message: 'Database check skipped'
            };
        }

        const allPassed = Object.values(checks).every(check =>
            check.status === 'pass' || check.status === 'optional' || check.status === 'info'
        );

        res.json({
            success: true,
            step: 1,
            title: 'System Requirements Check',
            checks,
            canProceed: allPassed,
            nextStep: allPassed ? 2 : null
        });

    } catch (error) {
        res.status(500).json({
            success: false,
            message: 'Requirements check failed',
            error: error.message
        });
    }
};

/**
 * Step 2: Configuration Form
 */
exports.configurationForm = async (req, res) => {
    try {
        // Simple configuration with only 3 essential variables
        const configSections = [
            {
                title: 'Basic Configuration',
                fields: [
                    {
                        name: 'NODE_ENV',
                        description: 'Application environment (development, production)',
                        defaultValue: 'development',
                        required: true,
                        type: 'select',
                        options: ['development', 'production', 'test']
                    },
                    {
                        name: 'MONGODB_URI',
                        description: 'MongoDB connection string',
                        defaultValue: 'mongodb://localhost:27017/cab_booking',
                        required: true,
                        type: 'text',
                        placeholder: 'mongodb://localhost:27017/your_database_name'
                    },
                    {
                        name: 'PORT',
                        description: 'Server port number',
                        defaultValue: '5000',
                        required: true,
                        type: 'number',
                        placeholder: '5000'
                    },
                    {
                        name: 'LICENCE_KEY',
                        description: 'Your licence key',
                        defaultValue: 'Lic-***************',
                        required: true,
                        type: 'text',
                        placeholder: 'Lic-****************'
                    },
                    {
                        name: 'DOMAIN',
                        description: 'Domain name of you platform',
                        defaultValue: 'example.com',
                        required: true,
                        type: 'text',
                        placeholder: 'example.com'
                    },
                    {
                        name: 'LICENSE_SERVER_URL',
                        description: 'URL of the licensing server (Servervault)',
                        defaultValue: 'https://servervault.com/api/verify',
                        required: true,
                        type: 'text',
                        placeholder: 'https://servervault.com/api/verify'
                    }
                ]
            }
        ];

        res.json({
            success: true,
            step: 2,
            title: 'Basic Configuration',
            description: 'Configure the essential settings for your Cab Booking System.',
            configSections,
            totalVariables: 3,
            nextStep: 3
        });

    } catch (error) {
        res.status(500).json({
            success: false,
            message: 'Configuration form generation failed',
            error: error.message
        });
    }
};

/**
 * Step 3: Generate ENV File and Connect Database
 */
exports.generateEnvExample = async (req, res) => {
    try {
        const { configData } = req.body;

        // Validate configuration first
        const validation = envGenerator.validateConfig(configData);
        if (!validation.isValid) {
            return res.status(400).json({
                success: false,
                message: 'Configuration validation failed',
                errors: validation.errors,
                warnings: validation.warnings
            });
        }

        // Generate actual .env file
        const result = await envGenerator.generateEnvExample(configData);

        // Try to connect to database with new configuration
        let databaseConnected = false;
        let databaseError = null;

        try {
            const mongoose = require('mongoose');

            // Disconnect existing connection if any
            if (mongoose.connection.readyState !== 0) {
                await mongoose.disconnect();
            }

            // Connect with new MONGODB_URI
            await mongoose.connect(configData.MONGODB_URI, {
                useNewUrlParser: true,
                useUnifiedTopology: true
            });

            databaseConnected = true;
            console.log('✅ Database connected successfully with new configuration');

        } catch (dbError) {
            databaseError = dbError.message;
            console.error('❌ Database connection failed:', dbError.message);
        }

        res.json({
            success: true,
            step: 3,
            title: 'Environment File Generated',
            description: 'Your .env file has been created and configuration loaded.',
            filePath: result.filePath,
            fileSize: result.fileSize,
            variablesCount: result.variablesCount,
            preview: result.preview,
            databaseConnected,
            databaseError,
            nextStep: 4,
            note: databaseConnected ?
                'Database connected successfully! Ready to finish installation.' :
                'Environment file created but database connection failed. Please check your MONGODB_URI.'
        });

    } catch (error) {
        res.status(500).json({
            success: false,
            message: 'ENV file generation failed',
            error: error.message
        });
    }
};

/**
 * Step 4: Finish Installation (Permanent Lock)
 */
exports.finishInstallation = async (req, res) => {
    try {
        const installedLockPath = path.join(process.cwd(), 'storage', 'installed.lock');
        const storageDir = path.dirname(installedLockPath);

        // Verify License before finishing installation
        const licenseResult = await verifyLicense();
        if (!licenseResult.valid) {
            return res.status(400).json({
                success: false,
                message: 'License Verification Failed. Please verify your LICENSE_KEY and DOMAIN in the config.',
                error: licenseResult.message
            });
        }

        // Ensure storage directory exists
        if (!fs.existsSync(storageDir)) {
            fs.mkdirSync(storageDir, { recursive: true });
        }

        // Create permanent installation lock file
        const installationData = {
            installedAt: new Date().toISOString(),
            version: '1.0.0',
            installerVersion: '1.0.0',
            configuredVariables: ['NODE_ENV', 'MONGODB_URI', 'PORT', 'LICENCE_KEY', 'DOMAIN', 'LICENSE_SERVER_URL'],
            permanent: true,
            note: 'Installation completed. Installer routes are now permanently locked.'
        };

        fs.writeFileSync(installedLockPath, JSON.stringify(installationData, null, 2));

        // Check final database connection status
        let finalDbStatus = 'unknown';
        try {
            const mongoose = require('mongoose');
            finalDbStatus = mongoose.connection.readyState === 1 ? 'connected' : 'disconnected';
        } catch (error) {
            finalDbStatus = 'error';
        }

        res.json({
            success: true,
            step: 4,
            title: 'Installation Complete - System Locked',
            description: 'The installation has completed successfully. Installer routes are now permanently locked.',
            summary: {
                envFileGenerated: true,
                installedLockCreated: true,
                systemReady: true,
                databaseStatus: finalDbStatus,
                installerLocked: true
            },
            nextSteps: [
                'Your .env file is configured and loaded',
                'Database connection has been established',
                'Installer routes are now permanently locked',
                'Your application is ready to use'
            ],
            warning: '⚠️ Installer routes are now permanently locked. To reinstall, you must manually delete storage/installed.lock file.',
            redirectUrl: '/super-admin',
            autoRedirectIn: 10
        });

    } catch (error) {
        res.status(500).json({
            success: false,
            message: 'Installation finish failed',
            error: error.message
        });
    }
};

/**
 * Get installer status
 */
exports.getStatus = async (req, res) => {
    try {
        const installedLockPath = path.join(process.cwd(), 'storage', 'installed.lock');
        const isInstalled = fs.existsSync(installedLockPath);

        let installationData = null;
        if (isInstalled) {
            try {
                const lockContent = fs.readFileSync(installedLockPath, 'utf8');
                installationData = JSON.parse(lockContent);
            } catch (error) {
                // Lock file exists but is invalid
                installationData = { corrupted: true };
            }
        }

        res.json({
            success: true,
            isInstalled,
            installationData,
            canReinstall: true,
            note: 'Remove storage/installed.lock to run installer again'
        });

    } catch (error) {
        res.status(500).json({
            success: false,
            message: 'Status check failed',
            error: error.message
        });
    }
};