#!/bin/bash

echo "=== Fixing bcryptjs and Completing Installation ==="

# Install bcryptjs in the backend directory
echo "Installing bcryptjs..."
cd /opt/airwavepbx/backend
sudo -u airwavepbx HOME=/home/airwavepbx npm install bcryptjs

# Initialize database
echo "Initializing database..."
cd /opt/airwavepbx

# Read the admin email from environment or use default
ADMIN_EMAIL=${ADMIN_EMAIL:-"admin@$(hostname -f)"}

cat > /tmp/setup-db.js << 'EOF'
const bcrypt = require('bcryptjs');
const database = require('./backend/src/models/database');
const config = require('./backend/src/config');
const logger = require('./backend/src/utils/logger');

async function setupDatabase() {
    try {
        logger.info('Setting up database...');
        
        database.initialize();
        
        const db = database.getConnection();
        const userCount = db.prepare('SELECT COUNT(*) as count FROM users').get().count;
        
        if (userCount === 0) {
            logger.info('Creating admin user...');
            
            const adminPassword = process.env.INITIAL_ADMIN_PASSWORD || 'changeme';
            const hashedPassword = await bcrypt.hash(adminPassword, config.auth.saltRounds);
            
            db.prepare(`
                INSERT INTO users (username, email, password, role)
                VALUES (?, ?, ?, ?)
            `).run('admin', process.env.ADMIN_EMAIL || 'admin@localhost', hashedPassword, 'admin');
            
            logger.info('Admin user created');
        }
        
        // Create sample extensions
        const extensions = [
            { extension: '1001', name: 'Reception', secret: generateSecret() },
            { extension: '1002', name: 'Sales', secret: generateSecret() },
            { extension: '1003', name: 'Support', secret: generateSecret() }
        ];
        
        const stmt = db.prepare(`
            INSERT OR IGNORE INTO extensions (extension, name, secret, context, mailbox)
            VALUES (?, ?, ?, ?, ?)
        `);
        
        extensions.forEach(ext => {
            stmt.run(ext.extension, ext.name, ext.secret, 'internal', ext.extension);
        });
        
        logger.info('Database setup completed successfully');
        
        database.close();
        process.exit(0);
    } catch (error) {
        logger.error('Database setup failed:', error);
        process.exit(1);
    }
}

function generateSecret() {
    return Array.from({ length: 16 }, () => 
        'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
            .charAt(Math.floor(Math.random() * 62))
    ).join('');
}

setupDatabase();
EOF

# Load environment variables from config.env
source /etc/airwavepbx/config.env

# Run database setup with proper environment
sudo -u airwavepbx HOME=/home/airwavepbx NODE_PATH=/opt/airwavepbx/backend/node_modules ADMIN_EMAIL="$ADMIN_EMAIL" INITIAL_ADMIN_PASSWORD="$INITIAL_ADMIN_PASSWORD" node /tmp/setup-db.js
rm -f /tmp/setup-db.js

# Start the service
echo "Starting AirwavePBX service..."
sudo systemctl daemon-reload
sudo systemctl start airwavepbx

echo "Waiting for service to start..."
sleep 10

# Check status
if systemctl is-active --quiet airwavepbx; then
    echo "✓ AirwavePBX service is running"
    
    # Get the domain from the config
    DOMAIN=$(grep "^DOMAIN=" /etc/airwavepbx/config.env | cut -d= -f2)
    ADMIN_PASSWORD=$(grep "INITIAL_ADMIN_PASSWORD=" /etc/airwavepbx/config.env | cut -d= -f2)
    
    echo ""
    echo "====================================="
    echo "AirwavePBX Installation Complete!"
    echo "====================================="
    echo ""
    echo "Access your system at: https://$DOMAIN"
    echo "Username: admin"
    echo "Password: $ADMIN_PASSWORD"
    echo ""
    echo "Run 'airwavepbx status' to check the service"
    echo "Run 'airwavepbx logs' to view logs"
else
    echo "✗ AirwavePBX service is not running"
    echo "Check logs with: journalctl -u airwavepbx -n 50"
    echo ""
    echo "If you see permission errors, run:"
    echo "sudo airwavepbx fix-permissions"
fi