/**
 * SocialMediaRepository
 * 
 * Repository für Social Media Platform und Consent Management
 * Verwaltet social_media_platforms und group_social_media_consents Tabellen
 */

class SocialMediaRepository {
    constructor(dbManager) {
        this.db = dbManager;
    }

    // ============================================================================
    // Platform Management
    // ============================================================================

    /**
     * Lade alle Social Media Plattformen (aktiv und inaktiv)
     * @returns {Promise<Array>} Array von Platform-Objekten
     */
    async getAllPlatforms() {
        const query = `
            SELECT 
                id,
                platform_name,
                display_name,
                icon_name,
                is_active,
                sort_order,
                created_at
            FROM social_media_platforms
            ORDER BY sort_order ASC, display_name ASC
        `;
        
        return await this.db.all(query);
    }

    /**
     * Lade nur aktive Social Media Plattformen
     * @returns {Promise<Array>} Array von aktiven Platform-Objekten
     */
    async getActivePlatforms() {
        const query = `
            SELECT 
                id,
                platform_name,
                display_name,
                icon_name,
                sort_order
            FROM social_media_platforms
            WHERE is_active = 1
            ORDER BY sort_order ASC, display_name ASC
        `;
        
        return await this.db.all(query);
    }

    /**
     * Erstelle eine neue Social Media Plattform
     * @param {Object} platformData - Platform-Daten
     * @param {string} platformData.platform_name - Interner Name (z.B. 'facebook')
     * @param {string} platformData.display_name - Anzeigename (z.B. 'Facebook')
     * @param {string} platformData.icon_name - Material-UI Icon Name
     * @param {number} platformData.sort_order - Sortierreihenfolge
     * @returns {Promise<number>} ID der neu erstellten Plattform
     */
    async createPlatform(platformData) {
        const query = `
            INSERT INTO social_media_platforms 
                (platform_name, display_name, icon_name, sort_order, is_active)
            VALUES (?, ?, ?, ?, 1)
        `;
        
        const result = await this.db.run(
            query,
            [
                platformData.platform_name,
                platformData.display_name,
                platformData.icon_name || null,
                platformData.sort_order || 0
            ]
        );
        
        return result.lastID;
    }

    /**
     * Aktualisiere eine bestehende Plattform
     * @param {number} platformId - ID der Plattform
     * @param {Object} platformData - Zu aktualisierende Daten
     * @returns {Promise<void>}
     */
    async updatePlatform(platformId, platformData) {
        const updates = [];
        const values = [];

        if (platformData.display_name !== undefined) {
            updates.push('display_name = ?');
            values.push(platformData.display_name);
        }
        if (platformData.icon_name !== undefined) {
            updates.push('icon_name = ?');
            values.push(platformData.icon_name);
        }
        if (platformData.sort_order !== undefined) {
            updates.push('sort_order = ?');
            values.push(platformData.sort_order);
        }

        if (updates.length === 0) {
            return; // Nichts zu aktualisieren
        }

        values.push(platformId);
        
        const query = `
            UPDATE social_media_platforms 
            SET ${updates.join(', ')}
            WHERE id = ?
        `;
        
        await this.db.run(query, values);
    }

    /**
     * Aktiviere oder deaktiviere eine Plattform
     * @param {number} platformId - ID der Plattform
     * @param {boolean} isActive - Aktiv-Status
     * @returns {Promise<void>}
     */
    async togglePlatformStatus(platformId, isActive) {
        const query = `
            UPDATE social_media_platforms 
            SET is_active = ?
            WHERE id = ?
        `;
        
        await this.db.run(query, [isActive ? 1 : 0, platformId]);
    }

    // ============================================================================
    // Consent Management
    // ============================================================================

    /**
     * Speichere Consents für eine Gruppe
     * @param {string} groupId - ID der Gruppe
     * @param {Array} consentsArray - Array von {platformId, consented} Objekten
     * @param {string} consentTimestamp - ISO-Timestamp der Zustimmung
     * @returns {Promise<void>}
     */
    async saveConsents(groupId, consentsArray, consentTimestamp) {
        if (!Array.isArray(consentsArray) || consentsArray.length === 0) {
            return; // Keine Consents zu speichern
        }

        const query = `
            INSERT INTO group_social_media_consents 
                (group_id, platform_id, consented, consent_timestamp)
            VALUES (?, ?, ?, ?)
        `;

        // Speichere jeden Consent einzeln
        for (const consent of consentsArray) {
            await this.db.run(
                query,
                [
                    groupId,
                    consent.platformId,
                    consent.consented ? 1 : 0,
                    consentTimestamp
                ]
            );
        }
    }

    /**
     * Lade alle Consents für eine Gruppe
     * @param {string} groupId - ID der Gruppe
     * @returns {Promise<Array>} Array von Consent-Objekten mit Platform-Info
     */
    async getConsentsForGroup(groupId) {
        const query = `
            SELECT 
                c.id,
                c.group_id,
                c.platform_id,
                c.consented,
                c.consent_timestamp,
                c.revoked,
                c.revoked_timestamp,
                p.platform_name,
                p.display_name,
                p.icon_name
            FROM group_social_media_consents c
            JOIN social_media_platforms p ON c.platform_id = p.id
            WHERE c.group_id = ?
            ORDER BY p.sort_order ASC
        `;
        
        return await this.db.all(query, [groupId]);
    }

    /**
     * Lade Gruppen-IDs nach Consent-Status filtern
     * @param {Object} filters - Filter-Optionen
     * @param {number} filters.platformId - Optional: Filter nach Plattform-ID
     * @param {boolean} filters.consented - Optional: Filter nach Consent-Status
     * @returns {Promise<Array>} Array von Gruppen-IDs
     */
    async getGroupIdsByConsentStatus(filters = {}) {
        let query = `
            SELECT DISTINCT c.group_id
            FROM group_social_media_consents c
            WHERE 1=1
        `;
        const params = [];

        if (filters.platformId !== undefined) {
            query += ' AND c.platform_id = ?';
            params.push(filters.platformId);
        }

        if (filters.consented !== undefined) {
            query += ' AND c.consented = ?';
            params.push(filters.consented ? 1 : 0);
        }

        if (filters.revoked !== undefined) {
            query += ' AND c.revoked = ?';
            params.push(filters.revoked ? 1 : 0);
        }

        const results = await this.db.all(query, params);
        return results.map(row => row.group_id);
    }

    /**
     * Widerrufe einen Consent (Phase 2)
     * @param {string} groupId - ID der Gruppe
     * @param {number} platformId - ID der Plattform
     * @returns {Promise<void>}
     */
    async revokeConsent(groupId, platformId) {
        const query = `
            UPDATE group_social_media_consents
            SET 
                revoked = 1,
                revoked_timestamp = CURRENT_TIMESTAMP
            WHERE group_id = ? AND platform_id = ?
        `;
        
        await this.db.run(query, [groupId, platformId]);
    }

    /**
     * Stelle einen widerrufenen Consent wieder her (Phase 2)
     * @param {string} groupId - ID der Gruppe
     * @param {number} platformId - ID der Plattform
     * @returns {Promise<void>}
     */
    async restoreConsent(groupId, platformId) {
        const query = `
            UPDATE group_social_media_consents
            SET 
                revoked = 0,
                revoked_timestamp = NULL
            WHERE group_id = ? AND platform_id = ?
        `;
        
        await this.db.run(query, [groupId, platformId]);
    }

    /**
     * Lade Consent-Historie für eine Gruppe (Phase 2)
     * @param {string} groupId - ID der Gruppe
     * @returns {Promise<Array>} Array von Consent-Änderungen
     */
    async getConsentHistory(groupId) {
        const query = `
            SELECT 
                c.id,
                c.group_id,
                c.platform_id,
                c.consented,
                c.consent_timestamp,
                c.revoked,
                c.revoked_timestamp,
                c.created_at,
                c.updated_at,
                p.platform_name,
                p.display_name
            FROM group_social_media_consents c
            JOIN social_media_platforms p ON c.platform_id = p.id
            WHERE c.group_id = ?
            ORDER BY c.updated_at DESC
        `;
        
        return await this.db.all(query, [groupId]);
    }

    /**
     * Prüfe ob eine Gruppe Consent für eine bestimmte Plattform hat
     * @param {string} groupId - ID der Gruppe
     * @param {number} platformId - ID der Plattform
     * @returns {Promise<boolean>} true wenn Consent erteilt und nicht widerrufen
     */
    async hasActiveConsent(groupId, platformId) {
        const query = `
            SELECT consented, revoked
            FROM group_social_media_consents
            WHERE group_id = ? AND platform_id = ?
        `;
        
        const result = await this.db.get(query, [groupId, platformId]);
        
        if (!result) {
            return false;
        }
        
        return result.consented === 1 && result.revoked === 0;
    }

    /**
     * Lösche alle Consents für eine Gruppe (CASCADE durch DB)
     * @param {string} groupId - ID der Gruppe
     * @returns {Promise<void>}
     */
    async deleteConsentsForGroup(groupId) {
        const query = `
            DELETE FROM group_social_media_consents
            WHERE group_id = ?
        `;
        
        await this.db.run(query, [groupId]);
    }
}

module.exports = SocialMediaRepository;
