const express = require('express');
const router = express.Router();
const database = require('../config/database');
const { auth, isAdmin } = require('../middleware/auth');

router.post('/', async (req, res) => {
    try {
        const { name, email, phone, subject, message } = req.body;
        await database.run(
            'INSERT INTO messages (name, email, phone, subject, message) VALUES (?, ?, ?, ?, ?)',
            [name, email, phone || null, subject || null, message]
        );
        res.status(201).json({ message: 'Message sent successfully' });
    } catch (error) {
        res.status(500).json({ error: 'Failed to send message' });
    }
});

router.get('/', auth, isAdmin, async (req, res) => {
    try {
        const messages = await database.all(
            'SELECT * FROM messages ORDER BY created_at DESC LIMIT 50'
        );
        res.json({ messages });
    } catch (error) {
        res.status(500).json({ error: 'Failed to fetch messages' });
    }
});

module.exports = router;
