/**
 * Teams Channel Poller
 * Polls Microsoft Graph API every 10 minutes to detect new channels in all Teams.
 * New channels are stored in teams_channels table with notified=0.
 */

const { getTeamsAllChannels } = require('./graph.service');
const { getDatabase } = require('../config/database');

async function pollTeamsChannels() {
    if (!process.env.AZURE_TENANT_ID || !process.env.AZURE_CLIENT_ID || !process.env.AZURE_CLIENT_SECRET) {
        return; // Azure not configured
    }

    try {
        const channels = await getTeamsAllChannels();
        const db = getDatabase();
        let newCount = 0;

        for (const ch of channels) {
            const existing = db.prepare('SELECT id FROM teams_channels WHERE channel_id = ?').get(ch.channelId);
            if (!existing) {
                db.prepare(`
                    INSERT INTO teams_channels (team_id, team_name, channel_id, channel_name, created_at_teams, first_seen_at, notified)
                    VALUES (?, ?, ?, ?, ?, datetime('now'), 0)
                `).run(ch.teamId, ch.teamName, ch.channelId, ch.channelName, ch.createdDateTime || null);
                newCount++;
                console.log(`[Teams] Neuer Kanal erkannt: "${ch.channelName}" in Team "${ch.teamName}"`);
            }
        }

        if (newCount > 0) {
            console.log(`[Teams] ${newCount} neue Kanal(e) gespeichert`);
        }
    } catch (err) {
        console.error('[Teams] Poll error:', err.message);
    }
}

/**
 * Initial sync: populate DB without marking as new (first run).
 * Marks all existing channels as notified=1 so only future ones trigger alerts.
 */
async function initialSync() {
    if (!process.env.AZURE_TENANT_ID || !process.env.AZURE_CLIENT_ID || !process.env.AZURE_CLIENT_SECRET) {
        return;
    }

    const db = getDatabase();
    const existing = db.prepare('SELECT COUNT(*) as c FROM teams_channels').get();
    if (existing.c > 0) return; // Already seeded

    try {
        console.log('[Teams] Initial sync – bestehende Kanäle einlesen...');
        const channels = await getTeamsAllChannels();
        const insert = db.prepare(`
            INSERT OR IGNORE INTO teams_channels (team_id, team_name, channel_id, channel_name, created_at_teams, first_seen_at, notified)
            VALUES (?, ?, ?, ?, ?, datetime('now'), 1)
        `);
        const insertMany = db.transaction((chs) => {
            for (const ch of chs) {
                insert.run(ch.teamId, ch.teamName, ch.channelId, ch.channelName, ch.createdDateTime || null);
            }
        });
        insertMany(channels);
        console.log(`[Teams] Initial sync abgeschlossen: ${channels.length} Kanäle eingelesen`);
    } catch (err) {
        console.error('[Teams] Initial sync error:', err.message);
    }
}

module.exports = { pollTeamsChannels, initialSync };
