/**
 * Consent Management API Routes
 * 
 * Handles social media platform listings and consent management
 */

const express = require('express');
const router = express.Router();
const GroupRepository = require('../repositories/GroupRepository');
const SocialMediaRepository = require('../repositories/SocialMediaRepository');
const dbManager = require('../database/DatabaseManager');
const { requireAdminAuth } = require('../middlewares/auth');
const { requireCsrf } = require('../middlewares/csrf');

// Schütze alle Consent-Routes mit Admin-Auth
router.use(requireAdminAuth);
router.use(requireCsrf);

// ============================================================================
// Social Media Platforms
// ============================================================================

/**
 * GET /social-media/platforms
 * Liste aller aktiven Social Media Plattformen
 */
router.get('/social-media/platforms', async (req, res) => {
    /* 
        #swagger.tags = ['Consent Management']
        #swagger.summary = 'Get active social media platforms'
        #swagger.description = 'Returns list of all active social media platforms available for consent'
        #swagger.responses[200] = {
            description: 'List of platforms',
            schema: [{
                platform_id: 1,
                platform_name: 'instagram',
                display_name: 'Instagram',
                icon_name: 'instagram',
                is_active: true
            }]
        }
    */
    try {
        const socialMediaRepo = new SocialMediaRepository(dbManager);
        const platforms = await socialMediaRepo.getActivePlatforms();
        
        res.json(platforms);
    } catch (error) {
        console.error('Error fetching platforms:', error);
        res.status(500).json({
            error: 'Failed to fetch social media platforms',
            message: error.message
        });
    }
});

// ============================================================================
// Group Consents
// ============================================================================

router.post('/groups/:groupId/consents', async (req, res) => {
    /* 
        #swagger.tags = ['Consent Management']
        #swagger.summary = 'Save or update consents for a group'
        #swagger.description = 'Store workshop consent and social media consents for a specific group'
        #swagger.parameters['groupId'] = {
            in: 'path',
            required: true,
            type: 'string',
            description: 'Group ID',
            example: 'abc123def456'
        }
        #swagger.parameters['body'] = {
            in: 'body',
            required: true,
            schema: {
                workshopConsent: true,
                socialMediaConsents: [
                    { platformId: 1, consented: true },
                    { platformId: 2, consented: false }
                ]
            }
        }
        #swagger.responses[200] = {
            description: 'Consents saved successfully',
            schema: { success: true, message: 'Consents saved successfully' }
        }
        #swagger.responses[400] = {
            description: 'Invalid request data'
        }
    */
    try {
        const { groupId } = req.params;
        const { workshopConsent, socialMediaConsents } = req.body;

        // Validierung
        if (typeof workshopConsent !== 'boolean') {
            return res.status(400).json({
                error: 'Invalid request',
                message: 'workshopConsent must be a boolean'
            });
        }

        if (!Array.isArray(socialMediaConsents)) {
            return res.status(400).json({
                error: 'Invalid request',
                message: 'socialMediaConsents must be an array'
            });
        }

        // Prüfe ob Gruppe existiert
        const group = await GroupRepository.getGroupById(groupId);
        if (!group) {
            return res.status(404).json({
                error: 'Group not found',
                message: `No group found with ID: ${groupId}`
            });
        }

        // Aktualisiere Consents
        await GroupRepository.updateConsents(
            groupId,
            workshopConsent,
            socialMediaConsents
        );

        res.json({
            success: true,
            message: 'Consents updated successfully',
            groupId
        });

    } catch (error) {
        console.error('Error updating consents:', error);
        res.status(500).json({
            error: 'Failed to update consents',
            message: error.message
        });
    }
});

/**
 * GET /groups/:groupId/consents
 * Lade alle Consents für eine Gruppe
 */
router.get('/groups/:groupId/consents', async (req, res) => {
    /* 
        #swagger.tags = ['Consent Management']
        #swagger.summary = 'Get consents for a group'
        #swagger.description = 'Returns all consent data (workshop + social media) for a specific group'
        #swagger.parameters['groupId'] = {
            in: 'path',
            required: true,
            type: 'string',
            description: 'Group ID',
            example: 'abc123def456'
        }
        #swagger.responses[200] = {
            description: 'Group consents',
            schema: {
                groupId: 'abc123',
                workshopConsent: true,
                consentTimestamp: '2025-11-01T10:00:00Z',
                socialMediaConsents: [{
                    platformId: 1,
                    platformName: 'instagram',
                    displayName: 'Instagram',
                    consented: true,
                    revoked: false
                }]
            }
        }
        #swagger.responses[404] = {
            description: 'Group not found'
        }
    */
    try {
        const { groupId } = req.params;

        // Hole Gruppe mit Consents
        const group = await GroupRepository.getGroupWithConsents(groupId);
        
        if (!group) {
            return res.status(404).json({
                error: 'Group not found',
                message: `No group found with ID: ${groupId}`
            });
        }

        // Formatiere Response
        const response = {
            groupId: group.group_id,
            workshopConsent: group.display_in_workshop === 1,
            consentTimestamp: group.consent_timestamp,
            socialMediaConsents: group.consents.map(c => ({
                platformId: c.platform_id,
                platformName: c.platform_name,
                displayName: c.display_name,
                iconName: c.icon_name,
                consented: c.consented === 1,
                consentTimestamp: c.consent_timestamp,
                revoked: c.revoked === 1,
                revokedTimestamp: c.revoked_timestamp
            }))
        };

        res.json(response);

    } catch (error) {
        console.error('Error fetching consents:', error);
        res.status(500).json({
            error: 'Failed to fetch consents',
            message: error.message
        });
    }
});

// ============================================================================
// Admin - Filtering & Export
// ============================================================================

/**
 * GET /groups/by-consent
 * Filtere Gruppen nach Consent-Status
 * 
 * Query params:
 *   - displayInWorkshop: boolean
 *   - platformId: number
 *   - platformConsent: boolean
 */
router.get('/groups/by-consent', async (req, res) => {
    /* 
        #swagger.tags = ['Consent Management']
        #swagger.summary = 'Filter groups by consent status'
        #swagger.description = 'Returns groups filtered by workshop consent or social media platform consents'
        #swagger.parameters['displayInWorkshop'] = {
            in: 'query',
            type: 'boolean',
            description: 'Filter by workshop consent',
            example: true
        }
        #swagger.parameters['platformId'] = {
            in: 'query',
            type: 'integer',
            description: 'Filter by platform ID',
            example: 1
        }
        #swagger.parameters['platformConsent'] = {
            in: 'query',
            type: 'boolean',
            description: 'Filter by platform consent status',
            example: true
        }
        #swagger.responses[200] = {
            description: 'Filtered groups',
            schema: {
                count: 5,
                filters: {
                    displayInWorkshop: true
                },
                groups: []
            }
        }
        #swagger.responses[400] = {
            description: 'Invalid platformId'
        }
    */
    try {
        const filters = {};

        // Parse query parameters
        if (req.query.displayInWorkshop !== undefined) {
            filters.displayInWorkshop = req.query.displayInWorkshop === 'true';
        }

        if (req.query.platformId !== undefined) {
            filters.platformId = parseInt(req.query.platformId, 10);
            
            if (isNaN(filters.platformId)) {
                return res.status(400).json({
                    error: 'Invalid platformId',
                    message: 'platformId must be a number'
                });
            }
        }

        if (req.query.platformConsent !== undefined) {
            filters.platformConsent = req.query.platformConsent === 'true';
        }

        // Hole gefilterte Gruppen
        const groups = await GroupRepository.getGroupsByConsentStatus(filters);

        res.json({
            count: groups.length,
            filters,
            groups
        });

    } catch (error) {
        console.error('Error filtering groups by consent:', error);
        res.status(500).json({
            error: 'Failed to filter groups',
            message: error.message
        });
    }
});

/**
 * GET /consents/export
 * Export Consent-Daten für rechtliche Dokumentation
 * 
 * Query params:
 *   - format: 'json' | 'csv' (default: json)
 *   - year: number (optional filter)
 *   - approved: boolean (optional filter)
 */
router.get('/consents/export', async (req, res) => {
    /* 
        #swagger.tags = ['Consent Management']
        #swagger.summary = 'Export consent data'
        #swagger.description = 'Exports consent data for legal documentation in JSON or CSV format'
        #swagger.parameters['format'] = {
            in: 'query',
            type: 'string',
            enum: ['json', 'csv'],
            description: 'Export format',
            example: 'json'
        }
        #swagger.parameters['year'] = {
            in: 'query',
            type: 'integer',
            description: 'Filter by year',
            example: 2025
        }
        #swagger.parameters['approved'] = {
            in: 'query',
            type: 'boolean',
            description: 'Filter by approval status',
            example: true
        }
        #swagger.responses[200] = {
            description: 'Export data (JSON format)',
            schema: {
                exportDate: '2025-11-15T16:30:00Z',
                filters: { year: 2025 },
                count: 12,
                data: []
            }
        }
        #swagger.responses[200] = {
            description: 'Export data (CSV format)',
            content: {
                'text/csv': {
                    schema: {
                        type: 'string',
                        format: 'binary'
                    }
                }
            }
        }
        #swagger.responses[400] = {
            description: 'Invalid format'
        }
    */
    try {
        const format = req.query.format || 'json';
        const filters = {};

        // Parse filters
        if (req.query.year) {
            filters.year = parseInt(req.query.year, 10);
        }

        if (req.query.approved !== undefined) {
            filters.approved = req.query.approved === 'true';
        }

        // Export Daten holen
        const exportData = await GroupRepository.exportConsentData(filters);

        // Format: JSON
        if (format === 'json') {
            res.json({
                exportDate: new Date().toISOString(),
                filters,
                count: exportData.length,
                data: exportData
            });
            return;
        }

        // Format: CSV
        if (format === 'csv') {
            // CSV Header
            let csv = 'group_id,year,title,name,upload_date,workshop_consent,consent_timestamp,approved';
            
            // Sammle alle möglichen Plattformen
            const allPlatforms = new Set();
            exportData.forEach(group => {
                group.socialMediaConsents.forEach(consent => {
                    allPlatforms.add(consent.platform_name);
                });
            });
            
            // Füge Platform-Spalten hinzu
            const platformNames = Array.from(allPlatforms).sort();
            platformNames.forEach(platform => {
                csv += `,${platform}`;
            });
            csv += '\n';

            // CSV Daten
            exportData.forEach(group => {
                const row = [
                    group.group_id,
                    group.year,
                    `"${(group.title || '').replace(/"/g, '""')}"`,
                    `"${(group.name || '').replace(/"/g, '""')}"`,
                    group.upload_date,
                    group.display_in_workshop === 1 ? 'true' : 'false',
                    group.consent_timestamp || '',
                    group.approved === 1 ? 'true' : 'false'
                ];

                // Platform-Consents
                const consentMap = {};
                group.socialMediaConsents.forEach(consent => {
                    // Consent ist nur dann aktiv wenn consented=1 UND nicht revoked
                    consentMap[consent.platform_name] = consent.consented === 1 && consent.revoked !== 1;
                });

                platformNames.forEach(platform => {
                    row.push(consentMap[platform] ? 'true' : 'false');
                });

                csv += row.join(',') + '\n';
            });

            res.setHeader('Content-Type', 'text/csv');
            res.setHeader('Content-Disposition', `attachment; filename=consent-export-${Date.now()}.csv`);
            res.send(csv);
            return;
        }

        res.status(400).json({
            error: 'Invalid format',
            message: 'Format must be "json" or "csv"'
        });

    } catch (error) {
        console.error('Error exporting consent data:', error);
        res.status(500).json({
            error: 'Failed to export consent data',
            message: error.message
        });
    }
});

module.exports = router;
