const { Router } = require('express');
const pool = require('../config/db');
const { authRequired, requireRole } = require('../middlewares/auth');

const router = Router();

// Categories
router.get('/categories', authRequired, async (req, res) => {
  const [c] = await pool.query('SELECT * FROM kb_categories ORDER BY sort_order');
  res.json(c);
});
router.post('/categories', authRequired, requireRole('admin'), async (req, res) => {
  const { name, description, icon } = req.body;
  const [r] = await pool.query('INSERT INTO kb_categories (name,description,icon) VALUES (?,?,?)', [name, description || null, icon || 'fa-folder']);
  res.status(201).json({ id: r.insertId });
});

// Articles LIST
router.get('/', authRequired, async (req, res) => {
  try {
    const { search, category, status } = req.query;
    let where = '1=1', params = [];
    if (!['admin', 'agent'].includes(req.user.role)) { where += " AND a.status='published'"; }
    else if (status) { where += ' AND a.status=?'; params.push(status); }
    if (category) { where += ' AND a.category_id=?'; params.push(category); }
    if (search) { where += ' AND (a.title LIKE ? OR a.content LIKE ?)'; params.push(`%${search}%`, `%${search}%`); }

    const [rows] = await pool.query(`SELECT a.*, c.name as category_name, c.icon as category_icon, u.name as author_name
      FROM kb_articles a LEFT JOIN kb_categories c ON a.category_id=c.id LEFT JOIN users u ON a.created_by=u.id
      WHERE ${where} ORDER BY a.is_pinned DESC, a.updated_at DESC`, params);
    res.json(rows);
  } catch (e) { console.error(e); res.status(500).json({ error: 'Error' }); }
});

// Article DETAIL
router.get('/:id', authRequired, async (req, res) => {
  const [a] = await pool.query('SELECT a.*, c.name as category_name, u.name as author_name FROM kb_articles a LEFT JOIN kb_categories c ON a.category_id=c.id LEFT JOIN users u ON a.created_by=u.id WHERE a.id=?', [req.params.id]);
  if (!a.length) return res.status(404).json({ error: 'No encontrado' });
  await pool.query('UPDATE kb_articles SET views=views+1 WHERE id=?', [req.params.id]);
  res.json(a[0]);
});

// CREATE
router.post('/', authRequired, requireRole('admin', 'agent'), async (req, res) => {
  const { title, content, category_id, status, is_pinned } = req.body;
  if (!title || !content) return res.status(400).json({ error: 'Título y contenido requeridos' });
  const [r] = await pool.query('INSERT INTO kb_articles (title,content,category_id,status,is_pinned,created_by) VALUES (?,?,?,?,?,?)',
    [title, content, category_id || null, status || 'draft', is_pinned ? 1 : 0, req.user.sub]);
  res.status(201).json({ id: r.insertId });
});

// UPDATE
router.put('/:id', authRequired, requireRole('admin', 'agent'), async (req, res) => {
  const { title, content, category_id, status, is_pinned } = req.body;
  await pool.query('UPDATE kb_articles SET title=?,content=?,category_id=?,status=?,is_pinned=? WHERE id=?',
    [title, content, category_id || null, status, is_pinned ? 1 : 0, req.params.id]);
  res.json({ message: 'Artículo actualizado' });
});

// HELPFUL vote
router.post('/:id/helpful', authRequired, async (req, res) => {
  const field = req.body.helpful ? 'helpful_yes' : 'helpful_no';
  await pool.query(`UPDATE kb_articles SET ${field}=${field}+1 WHERE id=?`, [req.params.id]);
  res.json({ message: 'Gracias' });
});

module.exports = router;
