const db = require('../db');

exports.createFeedback = async (req, res) => {
    const { message, type } = req.body;
    const userId = req.user.id;
    const username = req.user.username || req.user.name;

    if (!message) {
        return res.status(400).json({ message: 'Message is required' });
    }

    try {
        await db.query(
            'INSERT INTO feedbacks (user_id, username, message, type) VALUES (?, ?, ?, ?)',
            [userId, username, message, type || 'feedback']
        );
        res.status(201).json({ message: 'Feedback submitted successfully' });
    } catch (error) {
        console.error('Error creating feedback:', error);
        res.status(500).json({ message: 'Server error' });
    }
};

exports.getAllFeedbacks = async (req, res) => {
    try {
        const result = await db.query('SELECT * FROM feedbacks ORDER BY created_at DESC');
        res.json(result.rows);
    } catch (error) {
        console.error('Error fetching feedbacks:', error);
        res.status(500).json({ message: 'Server error' });
    }
};

exports.deleteFeedback = async (req, res) => {
    const { id } = req.params;
    try {
        await db.query('DELETE FROM feedbacks WHERE id = ?', [id]);
        res.json({ message: 'Feedback deleted successfully' });
    } catch (error) {
        console.error('Error deleting feedback:', error);
        res.status(500).json({ message: 'Server error' });
    }
};
