/**
 * 后台管理 — 仪表盘
 */
const router = require('express').Router();
const db = require('../db');
const { buildPushMessage } = require('../utils/pushTemplate');

router.get('/', (req, res) => {
  const stats = {
    merchants: db.prepare('SELECT COUNT(*) AS n FROM merchants').get().n,
    products: db.prepare('SELECT COUNT(*) AS n FROM products').get().n,
    channels: db.prepare('SELECT COUNT(*) AS n FROM tg_channels').get().n,
    tasks: db.prepare('SELECT COUNT(*) AS n FROM monitor_tasks').get().n,
    recentLogs: db.prepare(`SELECT COUNT(*) AS n FROM check_logs WHERE created_at >= datetime('now', '-1 day')`).get().n,
  };

  const sampleProduct = db.prepare(`
    SELECT p.*, m.name AS merchant_name,
           p.generated_aff_url AS product_aff_url,
           (
             SELECT url FROM aff_links a
             WHERE a.product_id = p.id AND a.platform = 'telegram'
             ORDER BY a.id DESC LIMIT 1
           ) AS tg_aff_url,
           (
             SELECT url FROM aff_links a
             WHERE a.product_id = p.id
             ORDER BY a.id DESC LIMIT 1
           ) AS any_aff_url
    FROM products p
    LEFT JOIN merchants m ON p.merchant_id = m.id
    ORDER BY p.id DESC LIMIT 1
  `).get();

  const preview = sampleProduct
    ? buildPushMessage({ ...sampleProduct, aff_url: sampleProduct.product_aff_url || sampleProduct.tg_aff_url || sampleProduct.any_aff_url || sampleProduct.buy_url || sampleProduct.url || null })
    : null;

  res.render('admin/index', { stats, preview });
});

module.exports = router;
