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

/**
 * TelegramNotificationService
 * 
 * Versendet automatische Benachrichtigungen über Telegram an die Werkstatt-Gruppe.
 * 
 * Features:
 * - Upload-Benachrichtigungen (Phase 3)
 * - Consent-Änderungs-Benachrichtigungen (Phase 4)
 * - Gruppen-Lösch-Benachrichtigungen (Phase 4)
 * - Tägliche Lösch-Warnungen (Phase 5)
 * 
 * Phase 2: Backend-Service Integration (Basic Setup)
 */
class TelegramNotificationService {
    constructor() {
        this.enabled = process.env.TELEGRAM_ENABLED === 'true';
        this.botToken = process.env.TELEGRAM_BOT_TOKEN;
        this.chatId = process.env.TELEGRAM_CHAT_ID;
        this.bot = null;

        if (this.enabled) {
            this.initialize();
        } else {
            console.log('[Telegram] Service disabled (TELEGRAM_ENABLED=false)');
        }
    }

    /**
     * Initialisiert den Telegram Bot
     */
    initialize() {
        try {
            if (!this.botToken) {
                throw new Error('TELEGRAM_BOT_TOKEN is not defined');
            }

            if (!this.chatId) {
                throw new Error('TELEGRAM_CHAT_ID is not defined');
            }

            this.bot = new TelegramBot(this.botToken, { polling: false });
            console.log('[Telegram] Service initialized successfully');
        } catch (error) {
            console.error('[Telegram] Initialization failed:', error.message);
            this.enabled = false;
        }
    }

    /**
     * Prüft, ob der Service verfügbar ist
     */
    isAvailable() {
        return this.enabled && this.bot !== null;
    }

    /**
     * Sendet eine Test-Nachricht
     * 
     * @returns {Promise<Object>} Telegram API Response
     */
    async sendTestMessage() {
        if (!this.isAvailable()) {
            console.log('[Telegram] Service not available, skipping test message');
            return null;
        }

        try {
            const timestamp = new Date().toLocaleString('de-DE', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
            });

            const message = `
🤖 Telegram Service Test

Service erfolgreich initialisiert!

Zeitstempel: ${timestamp}
Environment: ${process.env.NODE_ENV || 'development'}

---
ℹ️ Dieser Bot sendet automatische Benachrichtigungen für den Image Uploader.
`.trim();

            const response = await this.bot.sendMessage(this.chatId, message);
            console.log('[Telegram] Test message sent successfully');
            return response;
        } catch (error) {
            console.error('[Telegram] Failed to send test message:', error.message);
            throw error;
        }
    }

    /**
     * Phase 3: Sendet Benachrichtigung bei neuem Upload
     * 
     * @param {Object} groupData - Gruppen-Informationen
     * @param {string} groupData.name - Name des Uploaders
     * @param {number} groupData.year - Jahr der Gruppe
     * @param {string} groupData.title - Titel der Gruppe
     * @param {number} groupData.imageCount - Anzahl hochgeladener Bilder
     * @param {boolean} groupData.workshopConsent - Workshop-Consent Status
     * @param {Array<string>} groupData.socialMediaConsents - Social Media Plattformen
     * @param {string} groupData.token - Management-Token
     */
    async sendUploadNotification(groupData) {
        if (!this.isAvailable()) {
            console.log('[Telegram] Service not available, skipping upload notification');
            return null;
        }

        try {
            const workshopIcon = groupData.workshopConsent ? '✅' : '❌';
            const socialMediaIcons = this.formatSocialMediaIcons(groupData.socialMediaConsents);

            const message = `
📸 Neuer Upload!

Uploader: ${groupData.name}
Bilder: ${groupData.imageCount}
Gruppe: ${groupData.year} - ${groupData.title}

Workshop: ${workshopIcon} ${groupData.workshopConsent ? 'Ja' : 'Nein'}
Social Media: ${socialMediaIcons || '❌ Keine'}

🔗 Zur Freigabe: ${this.getAdminUrl()}
`.trim();

            const response = await this.bot.sendMessage(this.chatId, message);
            console.log(`[Telegram] Upload notification sent for group: ${groupData.title}`);
            return response;
        } catch (error) {
            console.error('[Telegram] Failed to send upload notification:', error.message);
            // Fehler loggen, aber nicht werfen - Upload soll nicht fehlschlagen wegen Telegram
            return null;
        }
    }

    /**
     * Phase 4: Sendet Benachrichtigung bei Consent-Änderung
     * 
     * @param {Object} changeData - Änderungs-Informationen
     * @param {string} changeData.name - Name des Uploaders
     * @param {number} changeData.year - Jahr
     * @param {string} changeData.title - Titel
     * @param {string} changeData.consentType - 'workshop' oder 'social_media'
     * @param {string} changeData.action - 'revoke' oder 'restore'
     * @param {string} [changeData.platform] - Plattform-Name (nur bei social_media)
     * @param {boolean} [changeData.newValue] - Neuer Wert (nur bei workshop)
     */
    async sendConsentChangeNotification(changeData) {
        if (!this.isAvailable()) {
            console.log('[Telegram] Service not available, skipping consent change notification');
            return null;
        }

        try {
            const { name, year, title, consentType, action, platform, newValue } = changeData;
            
            let changeDescription;
            if (consentType === 'workshop') {
                const icon = newValue ? '✅' : '❌';
                const status = newValue ? 'Ja' : 'Nein';
                const actionText = action === 'revoke' ? 'widerrufen' : 'wiederhergestellt';
                changeDescription = `Workshop-Consent ${actionText}\nNeuer Status: ${icon} ${status}`;
            } else if (consentType === 'social_media') {
                const actionText = action === 'revoke' ? 'widerrufen' : 'erteilt';
                changeDescription = `Social Media Consent ${actionText}\nPlattform: ${platform}`;
            }

            const message = `
⚙️ Consent-Änderung

Gruppe: ${year} - ${title}
Uploader: ${name}

${changeDescription}

🔗 Details: ${this.getAdminUrl()}
`.trim();

            const response = await this.bot.sendMessage(this.chatId, message);
            console.log(`[Telegram] Consent change notification sent for: ${title}`);
            return response;
        } catch (error) {
            console.error('[Telegram] Failed to send consent change notification:', error.message);
            throw error;
        }
    }

    /**
     * Phase 4: Sendet Benachrichtigung bei Gruppen-Löschung durch User
     * 
     * @param {Object} groupData - Gruppen-Informationen
     */
    async sendGroupDeletedNotification(groupData) {
        if (!this.isAvailable()) {
            console.log('[Telegram] Service not available, skipping group deleted notification');
            return null;
        }

        try {
            const message = `
⚙️ User-Änderung

Aktion: Gruppe gelöscht
Gruppe: ${groupData.year} - ${groupData.title}
Uploader: ${groupData.name}
Bilder: ${groupData.imageCount}

ℹ️ User hat Gruppe selbst über Management-Link gelöscht
`.trim();

            const response = await this.bot.sendMessage(this.chatId, message);
            console.log(`[Telegram] Group deleted notification sent for: ${groupData.title}`);
            return response;
        } catch (error) {
            console.error('[Telegram] Failed to send group deleted notification:', error.message);
            return null;
        }
    }

    /**
     * Phase 5: Sendet tägliche Warnung für bevorstehende Löschungen
     * 
     * @param {Array<Object>} groupsList - Liste der zu löschenden Gruppen
     */
    async sendDeletionWarning(groupsList) {
        if (!this.isAvailable()) {
            console.log('[Telegram] Service not available, skipping deletion warning');
            return null;
        }

        if (!groupsList || groupsList.length === 0) {
            console.log('[Telegram] No groups pending deletion, skipping warning');
            return null;
        }

        try {
            let groupsText = groupsList.map((group, index) => {
                const uploadDate = new Date(group.created_at).toLocaleDateString('de-DE');
                return `${index + 1}. ${group.year} - ${group.title}
   Uploader: ${group.name}
   Bilder: ${group.imageCount}
   Hochgeladen: ${uploadDate}`;
            }).join('\n\n');

            const message = `
⏰ Löschung in 24 Stunden!

Folgende Gruppen werden morgen automatisch gelöscht:

${groupsText}

💡 Jetzt freigeben oder Freigabe bleibt aus!
🔗 Zur Moderation: ${this.getAdminUrl()}
`.trim();

            const response = await this.bot.sendMessage(this.chatId, message);
            console.log(`[Telegram] Deletion warning sent for ${groupsList.length} groups`);
            return response;
        } catch (error) {
            console.error('[Telegram] Failed to send deletion warning:', error.message);
            return null;
        }
    }

    // =========================================================================
    // Helper Methods
    // =========================================================================

    /**
     * Formatiert Social Media Consents als Icons
     * 
     * @param {Array<string>} platforms - Liste der Plattformen
     * @returns {string} Formatierter String mit Icons
     */
    formatSocialMediaIcons(platforms) {
        if (!platforms || platforms.length === 0) {
            return '';
        }

        const iconMap = {
            'facebook': '📘 Facebook',
            'instagram': '📷 Instagram',
            'tiktok': '🎵 TikTok'
        };

        return platforms.map(p => iconMap[p.toLowerCase()] || p).join(', ');
    }

    /**
     * Gibt die Admin-URL zurück
     * 
     * @returns {string} Admin-Panel URL
     */
    getAdminUrl() {
        const host = process.env.INTERNAL_HOST || 'internal.hobbyhimmel.de';
        const isProduction = process.env.NODE_ENV === 'production';
        const protocol = isProduction ? 'https' : 'http';
        const port = isProduction ? '' : ':3000';
        return `${protocol}://${host}${port}/moderation`;
    }
}

module.exports = TelegramNotificationService;
