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

const router = Router();

// LIST
router.get('/', authRequired, requireRole('admin', 'agent'), async (req, res) => {
  try {
    const { type, status, search, assigned_to } = req.query;
    let where = '1=1', params = [];
    if (type) { where += ' AND a.type=?'; params.push(type); }
    if (status) { where += ' AND a.status=?'; params.push(status); }
    if (assigned_to) { where += ' AND a.assigned_to=?'; params.push(assigned_to); }
    if (search) { where += ' AND (a.name LIKE ? OR a.asset_tag LIKE ? OR a.serial_number LIKE ?)'; params.push(`%${search}%`, `%${search}%`, `%${search}%`); }

    const [rows] = await pool.query(`
      SELECT a.*, u.name as assigned_user,
        (SELECT COUNT(*) FROM tickets WHERE asset_id=a.id) as ticket_count,
        (SELECT COUNT(*) FROM asset_maintenance WHERE asset_id=a.id) as maint_count
      FROM assets a LEFT JOIN users u ON a.assigned_to=u.id WHERE ${where} ORDER BY a.name`, params);
    res.json(rows);
  } catch (e) { console.error(e); res.status(500).json({ error: 'Error' }); }
});

// DETAIL
router.get('/:id', authRequired, requireRole('admin', 'agent'), async (req, res) => {
  try {
    const [a] = await pool.query('SELECT a.*, u.name as assigned_user FROM assets a LEFT JOIN users u ON a.assigned_to=u.id WHERE a.id=?', [req.params.id]);
    if (!a.length) return res.status(404).json({ error: 'No encontrado' });
    const [maint] = await pool.query('SELECT m.*, u.name as performed_by_name FROM asset_maintenance m LEFT JOIN users u ON m.performed_by=u.id WHERE m.asset_id=? ORDER BY m.performed_at DESC', [req.params.id]);
    const [tickets] = await pool.query('SELECT t.id, t.subject, t.priority, ts.name as status_name, ts.color as status_color, t.created_at FROM tickets t JOIN ticket_statuses ts ON t.status_id=ts.id WHERE t.asset_id=? ORDER BY t.created_at DESC LIMIT 20', [req.params.id]);
    res.json({ ...a[0], maintenance: maint, tickets });
  } catch (e) { console.error(e); res.status(500).json({ error: 'Error' }); }
});

// CREATE
router.post('/', authRequired, requireRole('admin', 'agent'), async (req, res) => {
  try {
    const { name, type, asset_tag, serial_number, brand, model, status, location, assigned_to, purchase_date, warranty_until, ip_address, notes } = req.body;
    if (!name) return res.status(400).json({ error: 'Nombre requerido' });
    const tag = asset_tag || ('AST-' + Date.now().toString(36).toUpperCase());
    const [r] = await pool.query('INSERT INTO assets (name,type,asset_tag,serial_number,brand,model,status,location,assigned_to,purchase_date,warranty_until,ip_address,notes) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)',
      [name, type || 'other', tag, serial_number || null, brand || null, model || null, status || 'active', location || null, assigned_to || null, purchase_date || null, warranty_until || null, ip_address || null, notes || null]);
    await logAction(req.user.sub, req.user.name, 'asset_created', 'asset', r.insertId, null, { name, type }, req.ip);
    res.status(201).json({ id: r.insertId, message: 'Activo creado' });
  } catch (e) {
    if (e.code === 'ER_DUP_ENTRY') return res.status(400).json({ error: 'Tag de activo duplicado' });
    console.error(e); res.status(500).json({ error: 'Error' });
  }
});

// UPDATE
router.put('/:id', authRequired, requireRole('admin', 'agent'), async (req, res) => {
  try {
    const { name, type, asset_tag, serial_number, brand, model, status, location, assigned_to, purchase_date, warranty_until, ip_address, notes } = req.body;
    await pool.query('UPDATE assets SET name=?,type=?,asset_tag=?,serial_number=?,brand=?,model=?,status=?,location=?,assigned_to=?,purchase_date=?,warranty_until=?,ip_address=?,notes=? WHERE id=?',
      [name, type, asset_tag, serial_number || null, brand || null, model || null, status, location || null, assigned_to || null, purchase_date || null, warranty_until || null, ip_address || null, notes || null, req.params.id]);
    await logAction(req.user.sub, req.user.name, 'asset_updated', 'asset', +req.params.id, null, { name, status }, req.ip);
    res.json({ message: 'Activo actualizado' });
  } catch (e) { console.error(e); res.status(500).json({ error: 'Error' }); }
});

// ADD MAINTENANCE
router.post('/:id/maintenance', authRequired, requireRole('admin', 'agent'), async (req, res) => {
  try {
    const { type, description, cost, next_maintenance } = req.body;
    if (!description) return res.status(400).json({ error: 'Descripción requerida' });
    await pool.query('INSERT INTO asset_maintenance (asset_id,type,description,cost,performed_by,next_maintenance) VALUES (?,?,?,?,?,?)',
      [req.params.id, type || 'maintenance', description, cost || 0, req.user.sub, next_maintenance || null]);
    await logAction(req.user.sub, req.user.name, 'maintenance_added', 'asset', +req.params.id);
    res.status(201).json({ message: 'Mantenimiento registrado' });
  } catch (e) { console.error(e); res.status(500).json({ error: 'Error' }); }
});

module.exports = router;
