import Match3Service from '../services/match3Service.js';

function extractHashedUserId(req) {
    return req.headers?.userid;
}

class Match3Controller {
    constructor() {
        this.service = Match3Service;
        
        // Binde alle Methoden an die Klasse
        this.getCampaigns = this.getCampaigns.bind(this);
        this.getCampaign = this.getCampaign.bind(this);
        this.getLevel = this.getLevel.bind(this);
        this.getUserProgress = this.getUserProgress.bind(this);
        this.updateLevelProgress = this.updateLevelProgress.bind(this);
        this.getUserStats = this.getUserStats.bind(this);
        this.cleanupUserProgress = this.cleanupUserProgress.bind(this);
    }

    // Kampagnen-Endpunkte
    async getCampaigns(req, res) {
        try {
            const result = await this.service.getCampaigns();
            res.json({
                success: true,
                data: result
            });
        } catch (error) {
            console.error('Error in getCampaigns:', error);
            const status = error.status || 500;
            const message = error.message || 'Internal server error';
            res.status(status).json({
                success: false,
                message: message
            });
        }
    }

    async getCampaign(req, res) {
        try {
            const result = await this.service.getCampaign(req.params.id);
            res.json({
                success: true,
                data: result
            });
        } catch (error) {
            console.error('Error in getCampaign:', error);
            const status = error.status || 500;
            const message = error.message || 'Internal server error';
            res.status(status).json({
                success: false,
                message: message
            });
        }
    }

    async getLevel(req, res) {
        try {
            const result = await this.service.getLevel(req.params.id);
            res.json({
                success: true,
                data: result
            });
        } catch (error) {
            console.error('Error in getLevel:', error);
            const status = error.status || 500;
            const message = error.message || 'Internal server error';
            res.status(status).json({
                success: false,
                message: message
            });
        }
    }

    // Benutzer-spezifische Endpunkte
    async getUserProgress(req, res) {
        try {
            const userId = extractHashedUserId(req);
            if (!userId) {
                return res.status(401).json({
                    success: false,
                    message: 'User ID required'
                });
            }

            const result = await this.service.getUserProgress(userId, req.params.campaignId);
            res.json({
                success: true,
                data: result
            });
        } catch (error) {
            console.error('Error in getUserProgress:', error);
            const status = error.status || 500;
            const message = error.message || 'Internal server error';
            res.status(status).json({
                success: false,
                message: message
            });
        }
    }

    async updateLevelProgress(req, res) {
        try {
            const userId = extractHashedUserId(req);
            if (!userId) {
                return res.status(401).json({
                    success: false,
                    message: 'User ID required'
                });
            }

            const { score, moves, time, stars, securityHash, timestamp } = req.body;
            
            // Prüfe ob alle erforderlichen Sicherheitsdaten vorhanden sind
            if (!securityHash || !timestamp) {
                return res.status(400).json({
                    success: false,
                    message: 'Security validation data missing'
                });
            }

            const result = await this.service.updateLevelProgress(
                userId, 
                req.params.campaignId, 
                req.params.levelId, 
                score, 
                moves, 
                time, 
                stars,
                securityHash,
                timestamp
            );

            res.status(201).json({
                success: true,
                    data: result
            });
        } catch (error) {
            console.error('Error in updateLevelProgress:', error);
            const status = error.status || 500;
            const message = error.message || 'Internal server error';
            res.status(status).json({
                success: false,
                message: message
            });
        }
    }

    // Bereinige falsche Level-Abschlüsse für einen Benutzer
    async cleanupUserProgress(req, res) {
        try {
            const userId = extractHashedUserId(req);
            if (!userId) {
                return res.status(401).json({
                    success: false,
                    message: 'User ID required'
                });
            }

            const result = await this.service.cleanupUserProgress(userId, req.params.campaignId);
            
            if (result.success) {
                res.json({
                    success: true,
                    data: result
                });
            } else {
                res.status(400).json({
                    success: false,
                    message: result.message
                    });
            }
        } catch (error) {
            console.error('Error in cleanupUserProgress:', error);
            const status = error.status || 500;
            const message = error.message || 'Internal server error';
            res.status(status).json({
                success: false,
                message: message
            });
        }
    }

    async getUserStats(req, res) {
        try {
            const userId = extractHashedUserId(req);
            if (!userId) {
                return res.status(401).json({
                    success: false,
                    message: 'User ID required'
                });
            }

            const result = await this.service.getUserStats(userId);
            res.json({
                success: true,
                data: result
            });
        } catch (error) {
            console.error('Error in getUserStats:', error);
            const status = error.status || 500;
            const message = error.message || 'Internal server error';
            res.status(status).json({
                success: false,
                message: message
            });
        }
    }
}

export default Match3Controller;
