require('dotenv').config();
const http = require('http');
const Telegram = require('./application/controllers/Telegram');
const scheduler = require('./application/services/Scheduler');
const ServiceModule = require('./application/modules/ServiceModule');

const PORT = 3000;

/**
 * Telegram Webhook Server
 */
const server = http.createServer((req, res) => {
    const pathname = req.url.split('?')[0];
    const urlParts = pathname.split('/').filter(Boolean);
    const webhookCode = urlParts[urlParts.length - 1] || null;

    if (req.method === 'POST') {
        let body = '';
        req.on('data', chunk => {
            body += chunk.toString();
        });
        req.on('end', async () => {
            try {
                if (body && webhookCode) {
                    const update = JSON.parse(body);
                    await Telegram.handleWebhook(
                        update,
                        webhookCode
                    );
                }
            } catch (e) {
                console.error(
                    '[Webhook Error]',
                    e.message
                );
            }
            res.writeHead(200, {
                'Content-Type': 'text/plain'
            });
            res.end('OK');
        });
    } else {

        res.writeHead(404);
        res.end('Not Found');

    }
});


/**
 * Scheduler Init
 */
function startSchedulers() {
    scheduler.addJob(
        'tgju_market',
        async () => {
            await ServiceModule.syncTgjuMarket();
        },
        5 * 60 * 1000,
        10 * 60 * 1000
    );
    scheduler.start();
}

/**
 * Start Server
 */
server.listen(PORT, () => {

    console.log(`--- Server Started on Port ${PORT} ---`);
    console.log(`Waiting for Telegram Webhooks...`);

    startSchedulers();

});