/**
 * 前台公开路由 — 首页 / 产品列表 / 产品详情
 * 支持 /plans/:slug（优先）和 /plans/:id（兼容）
 */
const router = require('express').Router();
const db = require('../db');
const { getSiteTgUrl } = require('../utils/settings');

// 首页
router.get('/', (req, res) => {
  // 推荐产品
  const featured = db.prepare(`
    SELECT p.*, m.name AS merchant_name
    FROM products p
    LEFT JOIN merchants m ON p.merchant_id = m.id
    WHERE p.is_public = 1 AND p.is_featured = 1
    ORDER BY p.sort_order ASC, p.id DESC
    LIMIT 6
  `).all();

  // 最新产品
  const latest = db.prepare(`
    SELECT p.*, m.name AS merchant_name
    FROM products p
    LEFT JOIN merchants m ON p.merchant_id = m.id
    WHERE p.is_public = 1
    ORDER BY p.id DESC
    LIMIT 6
  `).all();

  const stats = {
    products: db.prepare('SELECT COUNT(*) AS n FROM products WHERE is_public = 1').get().n,
    merchants: db.prepare('SELECT COUNT(*) AS n FROM merchants').get().n,
  };

  // 获取 Telegram 频道链接
  const tgUrl = getSiteTgUrl();

  res.render('public/home', { featured, latest, stats, tgUrl });
});

// 产品列表
router.get('/plans', (req, res) => {
  const { merchant, location, q } = req.query;
  let where = 'WHERE p.is_public = 1';
  const params = [];

  if (merchant) {
    where += ' AND p.merchant_id = ?';
    params.push(merchant);
  }
  if (location) {
    where += ' AND p.location LIKE ?';
    params.push(`%${location}%`);
  }
  if (q) {
    where += ' AND (p.name LIKE ? OR p.spec_summary LIKE ? OR p.tags LIKE ?)';
    params.push(`%${q}%`, `%${q}%`, `%${q}%`);
  }

  const products = db.prepare(`
    SELECT p.*, m.name AS merchant_name
    FROM products p
    LEFT JOIN merchants m ON p.merchant_id = m.id
    ${where}
    ORDER BY p.sort_order ASC, p.id DESC
  `).all(...params);

  const merchants = db.prepare('SELECT DISTINCT m.id, m.name FROM merchants m INNER JOIN products p ON p.merchant_id = m.id WHERE p.is_public = 1 ORDER BY m.name').all();

  // 收集所有地区
  const allLocations = db.prepare("SELECT DISTINCT location FROM products WHERE is_public = 1 AND location IS NOT NULL AND location != ''").all().map(r => r.location);

  res.render('public/plans', { products, merchants, allLocations, query: req.query });
});

// 产品详情 — 支持 slug 和 id 双访问
router.get('/plans/:identifier', (req, res) => {
  const identifier = req.params.identifier;
  let product;

  // 先尝试按 slug 查找
  product = db.prepare(`
    SELECT p.*, m.name AS merchant_name, m.website AS merchant_website
    FROM products p
    LEFT JOIN merchants m ON p.merchant_id = m.id
    WHERE p.slug = ? AND p.is_public = 1
  `).get(identifier);

  // 如果没找到且 identifier 是纯数字，按 id 查找（兼容旧链接）
  if (!product && /^\d+$/.test(identifier)) {
    product = db.prepare(`
      SELECT p.*, m.name AS merchant_name, m.website AS merchant_website
      FROM products p
      LEFT JOIN merchants m ON p.merchant_id = m.id
      WHERE p.id = ? AND p.is_public = 1
    `).get(identifier);

    // 如果找到了且该产品有 slug，301 重定向到 slug 地址
    if (product && product.slug) {
      return res.redirect(301, `/plans/${product.slug}`);
    }
  }

  if (!product) {
    return res.status(404).render('public/404');
  }

  // 同商家其他产品
  const related = db.prepare(`
    SELECT p.*, m.name AS merchant_name
    FROM products p
    LEFT JOIN merchants m ON p.merchant_id = m.id
    WHERE p.merchant_id = ? AND p.id != ? AND p.is_public = 1
    ORDER BY p.sort_order ASC
    LIMIT 4
  `).all(product.merchant_id, product.id);

  res.render('public/detail', { product, related });
});

module.exports = router;
