/**
 * MikhMon WhatsApp Gateway Server
 * Self-hosted WhatsApp Gateway using Baileys
 * 
 * @author MikhMon Team
 * @license GPL-2.0
 */

require('dotenv').config();
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const { createWhatsAppClient } = require('./src/whatsapp');
const { createDatabase } = require('./src/database');
const routes = require('./src/routes');
const logger = require('./src/logger');

const app = express();
const PORT = process.env.PORT || 3000;
const HOST = process.env.HOST || '0.0.0.0';

// Middleware
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// Logging middleware
app.use((req, res, next) => {
    logger.info(`${req.method} ${req.path}`);
    next();
});

// Global state
global.whatsappClient = null;
global.qrCode = null;
global.isConnected = false;
global.connectionStatus = 'disconnected';
global.phoneNumber = null;

// Initialize database
const db = createDatabase();
global.db = db;

// Initialize WhatsApp client
async function initializeWhatsApp() {
    try {
        logger.info('Initializing WhatsApp client...');
        const client = await createWhatsAppClient();
        global.whatsappClient = client;
        logger.info('WhatsApp client initialized successfully');
    } catch (error) {
        logger.error('Failed to initialize WhatsApp client:', error);
        // Retry after 10 seconds
        setTimeout(initializeWhatsApp, 10000);
    }
}

// Routes
app.use('/api', routes);

// Health check
app.get('/health', (req, res) => {
    res.json({
        status: 'ok',
        whatsapp: {
            connected: global.isConnected,
            status: global.connectionStatus,
            phone: global.phoneNumber
        },
        uptime: process.uptime(),
        timestamp: new Date().toISOString()
    });
});

// Root endpoint
app.get('/', (req, res) => {
    res.json({
        name: 'MikhMon WhatsApp Gateway',
        version: '1.0.0',
        status: global.connectionStatus,
        connected: global.isConnected,
        phone: global.phoneNumber,
        endpoints: {
            health: '/health',
            qr: '/api/qr',
            status: '/api/status',
            send: '/api/send',
            sendBulk: '/api/send-bulk',
            logout: '/api/logout',
            restart: '/api/restart'
        }
    });
});

// Error handler
app.use((err, req, res, next) => {
    logger.error('Error:', err);
    res.status(500).json({
        success: false,
        message: 'Internal server error',
        error: err.message
    });
});

// Start server
app.listen(PORT, HOST, async () => {
    logger.info(`===========================================`);
    logger.info(`MikhMon WhatsApp Gateway Server`);
    logger.info(`===========================================`);
    logger.info(`Server running on http://${HOST}:${PORT}`);
    logger.info(`Environment: ${process.env.NODE_ENV || 'development'}`);
    logger.info(`===========================================`);
    
    // Initialize WhatsApp
    await initializeWhatsApp();
});

// Graceful shutdown
process.on('SIGINT', async () => {
    logger.info('Shutting down gracefully...');
    if (global.whatsappClient) {
        await global.whatsappClient.logout();
    }
    process.exit(0);
});

process.on('SIGTERM', async () => {
    logger.info('Shutting down gracefully...');
    if (global.whatsappClient) {
        await global.whatsappClient.logout();
    }
    process.exit(0);
});
