/**
 * Environment Generator Service
 * 
 * Generates .env.example file based on analyzed project structure
 * and user configuration input.
 * 
 * ⚠️ CONSTRAINT: Only generates .env.example, NOT .env file
 */

const fs = require('fs');
const path = require('path');

/**
 * Generate actual .env file (NOT .env.example)
 */
exports.generateEnvExample = async (configData = {}) => {
    try {
        const projectRoot = process.cwd();
        const envPath = path.join(projectRoot, '.env');

        // Generate content
        const content = generateEnvContent(configData);

        // Write to actual .env file
        fs.writeFileSync(envPath, content, 'utf8');

        // Get file stats
        const stats = fs.statSync(envPath);

        // Count variables
        const variablesCount = (content.match(/^[A-Z_][A-Z0-9_]*=/gm) || []).length;

        // Generate preview (first 20 lines)
        const lines = content.split('\n');
        const preview = lines.slice(0, 20).join('\n') + (lines.length > 20 ? '\n...' : '');

        // Reload environment variables immediately
        require('dotenv').config({ path: envPath });

        return {
            success: true,
            filePath: envPath,
            fileSize: stats.size,
            variablesCount,
            preview,
            message: '.env file generated and loaded successfully'
        };

    } catch (error) {
        throw new Error(`Failed to generate .env file: ${error.message}`);
    }
};

/**
 * Generate the content for .env file
 */
function generateEnvContent(configData) {
    const timestamp = new Date().toISOString();

    let content = `# Environment Configuration
# Generated by Cab Booking System Installer
# Generated on: ${timestamp}
#
# ⚠️ IMPORTANT: This is your actual .env file
# Keep this file secure and never commit to version control

# Basic Configuration
# ------------------

# Application environment (development, production, test)
NODE_ENV=${configData.NODE_ENV || 'development'}

# MongoDB connection string
MONGODB_URI=${configData.MONGODB_URI || 'mongodb://localhost:27017/cab_booking'}

# Server port number
PORT=${configData.PORT || '5000'}

# Licence configurations
LICENCE_KEY=${configData.LICENCE_KEY || ''}
DOMAIN=${configData.DOMAIN || ''}
LICENSE_SERVER_URL=${configData.LICENSE_SERVER_URL || ''}

# Additional Notes:
# - This file contains your actual configuration values
# - Keep sensitive information secure and never commit .env to version control
# - Server will automatically restart with new configuration
`;

    return content;
}

/**
 * Generate a section of environment variables
 */
function generateSection(title, variables) {
    let section = `\n# ${title}\n`;
    section += `# ${'-'.repeat(title.length)}\n`;

    for (const variable of variables) {
        if (variable.description) {
            section += `# ${variable.description}\n`;
        }
        section += `${variable.name}=${variable.value}\n\n`;
    }

    return section;
}

/**
 * Validate configuration data
 */
exports.validateConfig = (configData) => {
    const errors = [];
    const warnings = [];

    // Required fields validation
    const requiredFields = ['NODE_ENV', 'MONGODB_URI', 'PORT', 'LICENCE_KEY', 'DOMAIN', 'LICENSE_SERVER_URL'];

    for (const field of requiredFields) {
        if (!configData[field] || configData[field].trim() === '') {
            errors.push(`${field} is required`);
        }
    }

    // Format validation
    if (configData.PORT && isNaN(parseInt(configData.PORT))) {
        errors.push('PORT must be a valid number');
    }

    if (configData.MONGODB_URI && !configData.MONGODB_URI.startsWith('mongodb://') && !configData.MONGODB_URI.startsWith('mongodb+srv://')) {
        warnings.push('MONGODB_URI should start with mongodb:// or mongodb+srv://');
    }

    if (configData.NODE_ENV && !['development', 'production', 'test'].includes(configData.NODE_ENV)) {
        warnings.push('NODE_ENV should be development, production, or test');
    }

    return {
        isValid: errors.length === 0,
        errors,
        warnings
    };
};

/**
 * Check if string is a valid URL
 */
function isValidUrl(string) {
    try {
        new URL(string);
        return true;
    } catch (_) {
        return false;
    }
}

/**
 * Generate a secure random string for secrets
 */
exports.generateSecureSecret = (length = 64) => {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*';
    let result = '';
    for (let i = 0; i < length; i++) {
        result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return result;
};