
const fs = require('fs');
const path = require('path');
const TelegramBot = require('node-telegram-bot-api');

const filePath = path.join(__dirname, '../content/telegram_users.json');
const token = process.env.TELEGRAM_BOT_TOKEN;
const enabled = process.env.TELEGRAM_BOT === 'true';

let bot;

const telegramBot = {
    Initialize: initializeBot,
    updateUserDetails: updateUserDetails
};

function initializeBot() {
    if (!enabled) {
        console.log("Telegram bot is not enabled.");
        return;
    }
    bot = new TelegramBot(token, { polling: true });
    bot.on('message', handleMessage);
    bot.on('new_chat_members', handleNewChatMembers);
    bot.on('contact', handleContact);
    bot.onText(/start/, handleStartCommand);
}

function handleMessage(msg) {
    const chatId = msg.chat.id;
    console.log("received message from chatId = " + chatId);
}

function handleNewChatMembers(msg) {
    const chatId = msg.chat.id;
    msg.new_chat_members.forEach(member => {
        greetNewMember(chatId, member);
    });
}

function greetNewMember(chatId, member) {
    const userId = member.id;
    const welcomeMessage = `Welcome, ${member.first_name}!`;
    bot.restrictChatMember(chatId, userId, { can_send_messages: false });
    bot.sendMessage(chatId, welcomeMessage);
}

function handleContact(msg) {
    const chatId = msg.chat.id;
    if (msg.contact && msg.contact.phone_number) {
        updateUserDetails(chatId, msg.contact.phone_number);
    } else {
        bot.sendMessage(chatId, "You did not share your phone number.");
    }
}

function handleStartCommand(msg) {
    const chatId = msg.chat.id;
    const options = {
        reply_markup: {
            one_time_keyboard: true,
            keyboard: [
                [{ text: "Разбира се!", request_contact: true, one_time_keyboard: true }],
                ["Не сега"]
            ],
            resize_keyboard: true
        },
        parse_mode: 'Markdown'
    };

    bot.sendMessage(chatId, "Моля, потвърдете вашия телефонен номер:", options);
}

function updateUserDetails(chatId, phoneNumber) {
    fs.readFile(filePath, 'utf8', (err, data) => {
        let users = [];

        if (err && err.code !== 'ENOENT') {
            console.error("Error reading the file:", err);
            return;
        }

        try {
            if (!err) {
                users = JSON.parse(data);
            }
        } catch (e) {
            //failed to parse json. delete the file and create a new one
            console.error("Error parsing the file:", e);
            console.log("Deleting the file and creating a new one...");
            fs.unlinkSync(filePath);
        }

        const userIndex = users.findIndex(user => user.phoneNumber === phoneNumber);
        if (userIndex !== -1) {
            users[userIndex].chatId = chatId;
        } else {
            users.push({ chatId, phoneNumber });
        }

        fs.writeFile(filePath, JSON.stringify(users, null, 2), 'utf8', (writeErr) => {
            if (writeErr) {
                console.error("Error writing to the file:", writeErr);
                return;
            }

            console.log("User details updated.");
        });
    });
}

module.exports = { initializeBot, updateUserDetails };

module.exports = telegramBot;