const BaseModel = require('./BaseModel');
const axios = require('axios'); // برای ارسال درخواست‌های HTTP به تلگرام

/**
 * botModel - لایه عملیاتی ارتباط با API تلگرام
 */
class botModel extends BaseModel {
    constructor() {
        super();
        this.apiUrl = 'https://api.telegram.org/bot';
    }
    
    async getBotTokenByCode(webhookCode) {
        const sql = "SELECT bot_token FROM bots WHERE webhook_code = ? AND status = 1 LIMIT 1";
        const result = await this.query(sql, [webhookCode]);
        return result.length > 0 ? result[0].bot_token : null;
    }
    
    async getBotToken(botId) {
        const sql = "SELECT bot_token FROM bots WHERE id = ? AND status = 1 LIMIT 1";
        const result = await this.query(sql, [botId]);
        return result.length > 0 ? result[0].bot_token : null;
    }

    /**
     * متد پایه برای ارسال درخواست به تلگرام با توکن داینامیک
     */
    async callApi(token, method, data) {
        try {
            const response = await axios.post(`${this.apiUrl}${token}/${method}`, data);
            return response.data;
        } catch (error) {
            console.error(`[Telegram API Error]: ${error.response?.data?.description || error.message}`);
            return null;
        }
    }

    async sendMessage(token, chatId, text, replyToId = null) {
        const data = {
            chat_id: chatId,
            text: text,
            reply_to_message_id: replyToId,
            parse_mode: 'HTML'
        };
        return await this.callApi(token, 'sendMessage', data);
    }

    async sendPhoto(token, chatId, photo, caption = '') {
        const data = {
            chat_id: chatId,
            photo: photo,
            caption: caption,
            parse_mode: 'HTML'
        };
        return await this.callApi(token, 'sendPhoto', data);
    }
}

module.exports = new botModel();