const express = require('express');
const router = express.Router();
const { authenticateToken } = require('../middleware/auth');
const { asyncHandler } = require('../middleware/errorHandler');

router.use(authenticateToken);

// GET /api/feedback — alle Issues von GitHub laden
router.get('/', asyncHandler(async (req, res) => {
    const { state = 'open' } = req.query;
    const response = await fetch(`https://api.github.com/repos/SimonGCereda/IT-Nexus/issues?state=${state}&labels=feedback&per_page=50`, {
        headers: {
            'Authorization': `Bearer ${process.env.GITHUB_TOKEN}`,
            'Accept': 'application/vnd.github.v3+json'
        }
    });
    const issues = await response.json();
    res.json({ status: 'success', data: issues });
}));

// POST /api/feedback — neues Issue erstellen
router.post('/', asyncHandler(async (req, res) => {
    const { title, body, category } = req.body;
    const user = req.user;

    const labelMap = { bug: 'bug', feature: 'enhancement', idea: 'question' };
    const labels = ['feedback', labelMap[category] || 'feedback'];

    const issueBody = `**Gemeldet von:** ${user.first_name || ''} ${user.last_name || ''} (@${user.username})\n**Kategorie:** ${category}\n\n---\n\n${body}`;

    const response = await fetch(`https://api.github.com/repos/SimonGCereda/IT-Nexus/issues`, {
        method: 'POST',
        headers: {
            'Authorization': `Bearer ${process.env.GITHUB_TOKEN}`,
            'Accept': 'application/vnd.github.v3+json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ title, body: issueBody, labels })
    });
    const issue = await response.json();
    res.json({ status: 'success', data: issue });
}));

// PATCH /api/feedback/:id — Issue schließen/öffnen (nur Admin)
router.patch('/:id', asyncHandler(async (req, res) => {
    const { state } = req.body;
    const response = await fetch(`https://api.github.com/repos/SimonGCereda/IT-Nexus/issues/${req.params.id}`, {
        method: 'PATCH',
        headers: {
            'Authorization': `Bearer ${process.env.GITHUB_TOKEN}`,
            'Accept': 'application/vnd.github.v3+json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ state })
    });
    const issue = await response.json();
    res.json({ status: 'success', data: issue });
}));

module.exports = router;
