const express = require('express');
const { all, one } = require('../db');

const router = express.Router();

router.get('/dashboard', (req, res) => {
  const stats = one(`
    SELECT
      COUNT(*) AS asset_count,
      COALESCE(SUM(acquisition_cost), 0) AS total_cost,
      COALESCE(SUM(CASE WHEN status = 'disposed' THEN 1 ELSE 0 END), 0) AS disposed_count,
      COALESCE(SUM(CASE WHEN status = 'in_service' THEN 1 ELSE 0 END), 0) AS in_service_count
    FROM assets
  `);
  const byCategory = all('SELECT category, COUNT(*) AS count, COALESCE(SUM(acquisition_cost), 0) AS value FROM assets GROUP BY category ORDER BY value DESC');
  const byStatus = all('SELECT status, COUNT(*) AS count FROM assets GROUP BY status ORDER BY count DESC');
  const upcomingTasks = all(`
    SELECT t.*, a.asset_id, a.description
    FROM tasks t
    LEFT JOIN assets a ON a.id = t.asset_id
    WHERE t.status != 'complete'
    ORDER BY t.due_date IS NULL, t.due_date
    LIMIT 8
  `);
  const auditTrail = all('SELECT al.*, u.name AS actor_name FROM audit_logs al LEFT JOIN users u ON u.id = al.actor_id ORDER BY al.id DESC LIMIT 10');
  res.json({ stats, byCategory, byStatus, upcomingTasks, auditTrail });
});

module.exports = router;
