// src/routes/analytics.js
const crypto = require('crypto');
const express = require('express');
const db = require('../db');
const requireAdmin = require('../middleware/requireAdmin');
const rateLimit = require('../middleware/rateLimit');
const { clientIp } = require('../middleware/audit');

const router = express.Router();

const SALT = process.env.SESSION_SECRET || 'yst-analytics-salt';
function hashVisitor(ip, ua) {
  return crypto.createHash('sha256').update(`${SALT}:${ip}:${ua}`).digest('hex').slice(0, 24);
}
function detectDevice(ua = '') {
  const s = ua.toLowerCase();
  if (/ipad|tablet/.test(s)) return 'tablet';
  if (/mobi|android|iphone/.test(s)) return 'mobile';
  return 'desktop';
}

// PUBLIC — lightweight beacon called by /assets/analytics.js on every page.
// Never stores a raw IP address, only a salted/truncated hash, and drops
// any request that looks like it's coming from the admin dashboard itself.
router.post('/analytics/pageview', rateLimit({ windowMs: 60_000, max: 120 }), (req, res) => {
  try {
    const { path: pagePath, referrer } = req.body || {};
    if (!pagePath || typeof pagePath !== 'string' || pagePath.startsWith('/admin')) {
      return res.status(204).end();
    }
    const ua = String(req.headers['user-agent'] || '');
    db.prepare(`INSERT INTO page_views (path, referrer, device, visitor_hash) VALUES (?, ?, ?, ?)`).run(
      pagePath.slice(0, 200),
      referrer ? String(referrer).slice(0, 300) : null,
      detectDevice(ua),
      hashVisitor(clientIp(req), ua)
    );
    res.status(204).end();
  } catch (e) {
    res.status(204).end(); // analytics must never surface an error to visitors
  }
});

// ADMIN — aggregate summary powering the Analytics page.
router.get('/admin/analytics/summary', requireAdmin, (req, res) => {
  const totalViews = db.prepare('SELECT COUNT(*) AS n FROM page_views').get().n;
  const viewsToday = db.prepare("SELECT COUNT(*) AS n FROM page_views WHERE date(created_at) = date('now')").get().n;
  const uniqueVisitors30d = db.prepare(`
    SELECT COUNT(DISTINCT visitor_hash) AS n FROM page_views WHERE created_at >= datetime('now','-30 days')
  `).get().n;

  const dailySeries = db.prepare(`
    SELECT date(created_at) AS day, COUNT(*) AS views, COUNT(DISTINCT visitor_hash) AS visitors
    FROM page_views
    WHERE created_at >= datetime('now','-13 days')
    GROUP BY day ORDER BY day ASC
  `).all();

  const topPages = db.prepare(`
    SELECT path, COUNT(*) AS views FROM page_views
    WHERE created_at >= datetime('now','-30 days')
    GROUP BY path ORDER BY views DESC LIMIT 8
  `).all();

  const topReferrers = db.prepare(`
    SELECT COALESCE(NULLIF(TRIM(referrer), ''), 'Direct / none') AS referrer, COUNT(*) AS visits
    FROM page_views
    WHERE created_at >= datetime('now','-30 days')
    GROUP BY referrer ORDER BY visits DESC LIMIT 6
  `).all();

  const deviceBreakdown = db.prepare(`
    SELECT device, COUNT(*) AS n FROM page_views
    WHERE created_at >= datetime('now','-30 days')
    GROUP BY device
  `).all();

  res.json({ totalViews, viewsToday, uniqueVisitors30d, dailySeries, topPages, topReferrers, deviceBreakdown });
});

module.exports = router;
