const express = require('express');
const router = express.Router();
const db = require('../db/database');
const { requireAuth, requireAdmin } = require('../middleware/auth');

router.get('/', requireAuth, async (req, res) => {
  try {
    const [rows] = await db.query('SELECT * FROM faq WHERE is_active = TRUE ORDER BY order_index, id');
    res.json(rows);
  } catch (err) {
    res.status(500).json({ error: 'Failed to fetch FAQ' });
  }
});

router.post('/', requireAdmin, async (req, res) => {
  try {
    const { question, answer, order_index } = req.body;
    const [result] = await db.query(
      'INSERT INTO faq (question, answer, order_index) VALUES (?, ?, ?)',
      [question, answer, order_index || 0]
    );
    res.json({ success: true, id: result.insertId });
  } catch (err) {
    res.status(500).json({ error: 'Failed to create FAQ' });
  }
});

router.put('/:id', requireAdmin, async (req, res) => {
  try {
    const { question, answer, order_index, is_active } = req.body;
    await db.query(
      'UPDATE faq SET question=?, answer=?, order_index=?, is_active=? WHERE id=?',
      [question, answer, order_index || 0, is_active !== false, req.params.id]
    );
    res.json({ success: true });
  } catch (err) {
    res.status(500).json({ error: 'Failed to update FAQ' });
  }
});

router.delete('/:id', requireAdmin, async (req, res) => {
  try {
    await db.query('DELETE FROM faq WHERE id = ?', [req.params.id]);
    res.json({ success: true });
  } catch (err) {
    res.status(500).json({ error: 'Failed to delete FAQ' });
  }
});

module.exports = router;
