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

const router = Router();

// ── USERS ──
router.get('/users', authRequired, requireRole('admin'), async (req, res) => {
  const [u] = await pool.query('SELECT id,name,email,role,department,phone,active,last_login,created_at FROM users ORDER BY role,name');
  res.json(u);
});
router.post('/users', authRequired, requireRole('admin'), async (req, res) => {
  try {
    const { name, email, password, role, department, phone } = req.body;
    if (!name || !email || !password) return res.status(400).json({ error: 'Nombre, email y contraseña requeridos' });
    const hash = await bcrypt.hash(password, 10);
    const [r] = await pool.query('INSERT INTO users (name,email,password,role,department,phone) VALUES (?,?,?,?,?,?)',
      [name, email, hash, role || 'client', department || null, phone || null]);
    await logAction(req.user.sub, req.user.name, 'user_created', 'user', r.insertId, null, { name, email, role }, req.ip);
    res.status(201).json({ id: r.insertId, message: 'Usuario creado' });
  } catch (e) {
    if (e.code === 'ER_DUP_ENTRY') return res.status(400).json({ error: 'Email ya registrado' });
    console.error(e); res.status(500).json({ error: 'Error' });
  }
});
router.put('/users/:id', authRequired, requireRole('admin'), async (req, res) => {
  const { name, email, role, department, phone, active, password } = req.body;
  let q = 'UPDATE users SET name=?,email=?,role=?,department=?,phone=?,active=?';
  const p = [name, email, role, department || null, phone || null, active !== false ? 1 : 0];
  if (password) { q += ',password=?'; p.push(await bcrypt.hash(password, 10)); }
  p.push(req.params.id);
  await pool.query(q + ' WHERE id=?', p);
  res.json({ message: 'Usuario actualizado' });
});
router.put('/users/:id/toggle', authRequired, requireRole('admin'), async (req, res) => {
  const [u] = await pool.query('SELECT active FROM users WHERE id=?', [req.params.id]);
  if (!u.length) return res.status(404).json({ error: 'No encontrado' });
  await pool.query('UPDATE users SET active=? WHERE id=?', [u[0].active ? 0 : 1, req.params.id]);
  res.json({ message: 'OK' });
});

// ── STATUSES ──
router.get('/statuses', authRequired, async (req, res) => {
  const [s] = await pool.query('SELECT * FROM ticket_statuses ORDER BY sort_order');
  res.json(s);
});
router.post('/statuses', authRequired, requireRole('admin'), async (req, res) => {
  const { name, color, icon, sort_order, is_default, is_closed } = req.body;
  const [r] = await pool.query('INSERT INTO ticket_statuses (name,color,icon,sort_order,is_default,is_closed) VALUES (?,?,?,?,?,?)',
    [name, color || '#6B7280', icon || 'fa-circle', sort_order || 0, is_default ? 1 : 0, is_closed ? 1 : 0]);
  res.status(201).json({ id: r.insertId });
});

// ── CATEGORIES ──
router.get('/categories', authRequired, async (req, res) => {
  const [c] = await pool.query('SELECT * FROM ticket_categories WHERE active=1 ORDER BY sort_order, name');
  res.json(c);
});
router.post('/categories', authRequired, requireRole('admin'), async (req, res) => {
  const { name, description, parent_id, icon, color } = req.body;
  const [r] = await pool.query('INSERT INTO ticket_categories (name,description,parent_id,icon,color) VALUES (?,?,?,?,?)',
    [name, description || null, parent_id || null, icon || 'fa-tag', color || '#6B7280']);
  res.status(201).json({ id: r.insertId });
});

// ── SLA ──
router.get('/sla', authRequired, requireRole('admin'), async (req, res) => {
  const [s] = await pool.query('SELECT * FROM sla_policies ORDER BY FIELD(priority,"critical","high","medium","low")');
  res.json(s);
});
router.post('/sla', authRequired, requireRole('admin'), async (req, res) => {
  const { name, priority, response_hours, resolution_hours, is_default } = req.body;
  const [r] = await pool.query('INSERT INTO sla_policies (name,priority,response_hours,resolution_hours,is_default) VALUES (?,?,?,?,?)',
    [name, priority, response_hours, resolution_hours, is_default ? 1 : 0]);
  res.status(201).json({ id: r.insertId });
});

// ── SETTINGS ──
router.get('/settings', authRequired, requireRole('admin'), async (req, res) => {
  const [s] = await pool.query('SELECT skey, svalue FROM settings');
  const obj = {}; s.forEach(r => obj[r.skey] = r.svalue);
  res.json(obj);
});
router.put('/settings', authRequired, requireRole('admin'), async (req, res) => {
  for (const [k, v] of Object.entries(req.body)) {
    await pool.query('INSERT INTO settings (skey,svalue) VALUES (?,?) ON DUPLICATE KEY UPDATE svalue=?', [k, v, v]);
  }
  res.json({ message: 'Configuración guardada' });
});

// ── AUDIT ──
router.get('/audit', authRequired, requireRole('admin'), async (req, res) => {
  const { entity_type, entity_id, limit: lim = 50 } = req.query;
  let where = '1=1', params = [];
  if (entity_type) { where += ' AND entity_type=?'; params.push(entity_type); }
  if (entity_id) { where += ' AND entity_id=?'; params.push(entity_id); }
  const [logs] = await pool.query(`SELECT * FROM audit_log WHERE ${where} ORDER BY created_at DESC LIMIT ?`, [...params, +lim]);
  res.json(logs);
});

// ── AGENTS (for dropdowns) ──
router.get('/agents', authRequired, async (req, res) => {
  const [a] = await pool.query("SELECT id,name,email,department FROM users WHERE role IN ('admin','agent') AND active=1 ORDER BY name");
  res.json(a);
});

module.exports = router;
