const { Router } = require('express');
const GroupRepository = require('../repositories/GroupRepository');
const MigrationService = require('../services/MigrationService');

const router = Router();

// Alle Gruppen abrufen (für Slideshow mit vollständigen Bilddaten)
router.get('/groups', async (req, res) => {
    /*
        #swagger.tags = ['Public Groups']
        #swagger.summary = 'Get approved groups with images'
        #swagger.description = 'Returns all approved groups (slideshow feed). Automatically triggers JSON→SQLite migration if required.'
        #swagger.responses[200] = {
            description: 'List of approved groups',
            schema: {
                groups: [{ groupId: 'cTV24Yn-a', title: 'Familie Mueller' }],
                totalCount: 73
            }
        }
        #swagger.responses[500] = { description: 'Server error' }
    */
    try {
        // Auto-Migration beim ersten Zugriff
        const migrationStatus = await MigrationService.getMigrationStatus();
        if (migrationStatus.needsMigration) {
            console.log('🔄 Starte automatische Migration...');
            await MigrationService.migrateJsonToSqlite();
        }

        const groups = await GroupRepository.getAllGroupsWithImages();
        res.json({
            groups,
            totalCount: groups.length
        });
    } catch (error) {
        console.error('Error fetching all groups:', error);
        res.status(500).json({ 
            error: 'Internal server error',
            message: 'Fehler beim Laden der Gruppen',
            details: error.message 
        });
    }
});

// Einzelne Gruppe abrufen (nur freigegebene)
router.get('/groups/:groupId', async (req, res) => {
    /*
        #swagger.tags = ['Public Groups']
        #swagger.summary = 'Get approved group by ID'
        #swagger.parameters['groupId'] = {
            in: 'path',
            required: true,
            type: 'string',
            description: 'Public groupId (e.g. cTV24Yn-a)'
        }
        #swagger.responses[200] = { description: 'Group payload (images + metadata)' }
        #swagger.responses[404] = { description: 'Group not found or not approved' }
        #swagger.responses[500] = { description: 'Server error' }
    */
    try {
        const { groupId } = req.params;
        const group = await GroupRepository.getGroupById(groupId);
        
        if (!group) {
            return res.status(404).json({ 
                error: 'Group not found',
                message: `Gruppe mit ID ${groupId} wurde nicht gefunden` 
            });
        }
        
        res.json(group);
    } catch (error) {
        console.error('Error fetching group:', error);
        res.status(500).json({ 
            error: 'Internal server error',
            message: 'Fehler beim Laden der Gruppe',
            details: error.message 
        });
    }
});

module.exports = router;
