/**
 * routes/dashboard.js
 * Main landing after login. Server picks the right HTML shell based on role.
 * The data API (/summary) returns the same shape; the frontend chooses what
 * to render.
 */

'use strict';

const path     = require('path');
const express  = require('express');
const { requireLogin } = require('../middleware/auth');
const Case     = require('../models/case');
const usageLog = require('../models/usageLog');
const Takedown = require('../models/takedown');
const Finding  = require('../models/finding');
const { getPlan, listPlans } = require('../config/plans');
const { db } = require('../config/db');

const router = express.Router();

router.get('/', requireLogin, (req, res) => {
  // Customers and superadmins get different shells.
  const view = req.user.role === 'superadmin' ? 'admin-dashboard.html' : 'dashboard.html';
  res.sendFile(path.join(__dirname, '..', 'public', 'views', view));
});

router.get('/sessions', requireLogin, (req, res) => {
  res.sendFile(path.join(__dirname, '..', 'public', 'views', 'dashboard-sessions.html'));
});

router.get('/summary', requireLogin, (req, res) => {
  const plan  = getPlan(req.user.plan, req.user.plan_override);
  const usage = usageLog.forUser(req.user.id);
  const cases = Case.listForUser(req.user.id, 10, 0);
  const activeCases = Case.activeCountForUser(req.user.id);
  // Full takedown list (not just 5) so the dashboard can render the
  // full state-machine history. Superadmins see everything across
  // the platform; customers see their own.
  const isSuper = req.user.role === 'superadmin';
  const tds   = isSuper
    ? Takedown.listAllTakedowns(100, 0)
    : Takedown.listForUser(req.user.id, 100, 0);
  const findings = db.prepare(`
    SELECT id, url, domain, tier, is_ncii, status, created_at
      FROM findings WHERE user_id = ? AND is_ncii = 1
     ORDER BY created_at DESC LIMIT 5
  `).all(req.user.id);

  // Takedown state breakdown — counts by status
  const statusBreakdown = db.prepare(`
    SELECT status, COUNT(*) as n FROM takedowns
     ${isSuper ? '' : 'WHERE user_id = ?'}
     GROUP BY status
  `).all(...(isSuper ? [] : [req.user.id]));

  // Per-domain summary for the "Takedowns" history panel. Joins
  // the latest link_health_checks so the dashboard can show
  // "removed" / "live" / "blocked" badges next to each takedown.
  const takedownHistory = db.prepare(`
    SELECT
      t.id, t.case_id, t.url, t.domain, t.contact_email, t.status,
      t.created_at, t.sent_at, t.escalated_at, t.resolved_at, t.next_escalate_at, t.error,
      (SELECT status FROM link_health_checks WHERE takedown_id = t.id ORDER BY checked_at DESC LIMIT 1) as last_health_status,
      (SELECT checked_at FROM link_health_checks WHERE takedown_id = t.id ORDER BY checked_at DESC LIMIT 1) as last_health_check,
      (SELECT http_status FROM link_health_checks WHERE takedown_id = t.id ORDER BY checked_at DESC LIMIT 1) as last_http_status,
      (SELECT reason FROM link_health_checks WHERE takedown_id = t.id ORDER BY checked_at DESC LIMIT 1) as last_health_reason
    FROM takedowns t
    ${isSuper ? '' : 'WHERE t.user_id = ?'}
    ORDER BY t.sent_at DESC NULLS LAST, t.created_at DESC
    LIMIT 200
  `).all(...(isSuper ? [] : [req.user.id]));

  const whereUser = isSuper ? '' : 'WHERE user_id = ?';
  const userParams = isSuper ? [] : [req.user.id];
  const takedownTotals = db.prepare(`
    SELECT
      COUNT(*) AS total,
      SUM(CASE WHEN status = 'removed' THEN 1 ELSE 0 END) AS removed,
      SUM(CASE WHEN status = 'responded' THEN 1 ELSE 0 END) AS responded,
      SUM(CASE WHEN status IN ('sent','escalated') THEN 1 ELSE 0 END) AS in_flight,
      SUM(CASE WHEN status IN ('queued','production_pending','manual_required','manual-required','chain_only') THEN 1 ELSE 0 END) AS pending,
      SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) AS failed,
      AVG(CASE WHEN resolved_at IS NOT NULL AND sent_at IS NOT NULL THEN (resolved_at - sent_at) / 3600000.0 END) AS avg_removed_hours
    FROM takedowns
    ${whereUser}
  `).get(...userParams);

  const liveHealth = db.prepare(`
    SELECT
      SUM(CASE WHEN latest.status = 'live' THEN 1 ELSE 0 END) AS live,
      SUM(CASE WHEN latest.status IN ('blocked','dns_fail','error') THEN 1 ELSE 0 END) AS uncertain,
      SUM(CASE WHEN latest.status IN ('removed','soft_404') THEN 1 ELSE 0 END) AS health_removed
    FROM (
      SELECT t.id,
             (SELECT status FROM link_health_checks WHERE takedown_id = t.id ORDER BY checked_at DESC LIMIT 1) AS status
      FROM takedowns t
      ${isSuper ? '' : 'WHERE t.user_id = ?'}
    ) latest
  `).get(...userParams);

  const domainStats = db.prepare(`
    SELECT domain,
           COUNT(*) AS total,
           SUM(CASE WHEN status = 'removed' THEN 1 ELSE 0 END) AS removed,
           SUM(CASE WHEN status IN ('sent','escalated') THEN 1 ELSE 0 END) AS in_flight,
           SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) AS failed
      FROM takedowns
     ${whereUser}
     GROUP BY domain
     ORDER BY total DESC, removed DESC
     LIMIT 8
  `).all(...userParams);

  const recentRemoved = db.prepare(`
    SELECT id, case_id, url, domain, contact_email, resolved_at, sent_at
      FROM takedowns
     ${isSuper ? "WHERE status = 'removed'" : "WHERE user_id = ? AND status = 'removed'"}
     ORDER BY resolved_at DESC NULLS LAST, updated_at DESC NULLS LAST
     LIMIT 8
  `).all(...userParams);

  const total = takedownTotals.total || 0;
  const resolved = (takedownTotals.removed || 0) + (takedownTotals.responded || 0);
  const takedownMetrics = {
    total,
    removed: takedownTotals.removed || 0,
    responded: takedownTotals.responded || 0,
    in_flight: takedownTotals.in_flight || 0,
    pending: takedownTotals.pending || 0,
    failed: takedownTotals.failed || 0,
    still_live: liveHealth.live || 0,
    uncertain: liveHealth.uncertain || 0,
    health_removed: liveHealth.health_removed || 0,
    success_rate: total ? Math.round((resolved / total) * 100) : 0,
    avg_removed_hours: takedownTotals.avg_removed_hours === null ? null : Number(takedownTotals.avg_removed_hours.toFixed(1)),
    by_domain: domainStats,
    recent_removed: recentRemoved,
  };

  res.json({
    user: req.user,
    plan,
    usage,
    active_cases: activeCases,
    limits: {
      cases:     plan.cases_limit,
      scans:     plan.scans_limit,
      takedowns: plan.takedowns_limit,
    },
    recent_cases:    cases.map(c => ({
      id: c.id, victim_name: c.victim_name, status: c.status,
      created_at: c.created_at, reference_url: c.reference_url,
    })),
    recent_takedowns: tds.slice(0, 5).map(t => ({
      id: t.id, url: t.url, domain: t.domain, status: t.status,
      sent_at: t.sent_at, created_at: t.created_at,
    })),
    takedown_history:    takedownHistory,            // full list, latest first
    takedown_breakdown:  statusBreakdown,            // for KPI cards
    takedown_metrics:    takedownMetrics,
    recent_findings: findings,
    plans: listPlans(),
  });
});

module.exports = router;
