const router = require('express').Router();
const db = require('../db');
const { buildPushMessage } = require('../utils/pushTemplate');
const { autoFillPidFields, parseProviderPid } = require('../utils/pidHelper');
const { parseAffCode, buildAffUrl } = require('../utils/affHelper');

function getProducts() {
  return 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.sort_order ASC, p.id DESC
  `).all().map((p) => {
    // 计算最终 aff 链接优先级：1. 产品生成的 aff 链接 2. aff_links 表 3. buy_url
    let aff_url = p.product_aff_url || p.tg_aff_url || p.any_aff_url || null;
    // 生成的完整 aff 链接（始终计算，用于展示）
    const generated_aff_url = p.product_aff_url || ((p.aff_code && p.buy_url)
      ? buildAffUrl(p.buy_url, p.aff_code, p.aff_param || 'aff')
      : null);

    return {
      ...p,
      aff_url,
      generated_aff_url,
      push_preview: buildPushMessage({ ...p, aff_url })
    };
  });
}

router.get('/', (req, res) => {
  const products = getProducts();
  const merchants = db.prepare('SELECT id, name FROM merchants ORDER BY name').all();
  res.render('admin/products', { products, merchants });
});

// 新增产品
router.post('/', (req, res) => {
  const {
    merchant_id, name, url, buy_url, sku, price, annual_price, location,
    spec_summary, traffic, billing_cycle, coupon_code, tags, push_intro, notes,
    check_mode, in_stock_keywords, out_of_stock_keywords,
    is_public, is_featured, sort_order
  } = req.body;

  if (!name || !merchant_id) return res.redirect('/admin/products');

  // 自动填充 PID 字段
  const pidFields = autoFillPidFields(db, {
    internal_pid: req.body.internal_pid || null,
    slug: req.body.slug || null,
    provider_pid: req.body.provider_pid || null,
    name,
    merchant_id,
    buy_url,
    url,
  });

  // 处理 aff_code：用户填的优先，否则从 buy_url 自动解析
  let aff_code = req.body.aff_code || null;
  let aff_param = req.body.aff_param || 'aff';
  if (!aff_code && buy_url) {
    const parsed = parseAffCode(buy_url);
    if (parsed) {
      aff_code = parsed.value;
      aff_param = parsed.param;
    }
  }

  // 计算生成的 aff 链接
  const generated_aff_url = (aff_code && buy_url)
    ? buildAffUrl(buy_url, aff_code, aff_param)
    : null;

  db.prepare(`
    INSERT INTO products (
      merchant_id, name, url, buy_url, sku, price, annual_price, location,
      spec_summary, traffic, billing_cycle, coupon_code, tags, push_intro, notes,
      check_mode, in_stock_keywords, out_of_stock_keywords,
      is_public, is_featured, sort_order,
      internal_pid, provider_pid, slug,
      aff_code, aff_param, generated_aff_url
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  `).run(
    merchant_id,
    name,
    url || null,
    buy_url || null,
    sku || null,
    price || null,
    annual_price || null,
    location || null,
    spec_summary || null,
    traffic || null,
    billing_cycle || null,
    coupon_code || null,
    tags || null,
    push_intro || null,
    notes || null,
    check_mode || 'keyword',
    in_stock_keywords || null,
    out_of_stock_keywords || null,
    is_public ? 1 : 0,
    is_featured ? 1 : 0,
    parseInt(sort_order, 10) || 100,
    pidFields.internal_pid,
    pidFields.provider_pid || null,
    pidFields.slug,
    aff_code || null,
    aff_param || 'aff',
    generated_aff_url
  );

  // 自动创建 aff_link 记录（如果有 aff_code 且 buy_url）
  if (aff_code && buy_url) {
    const newProduct = db.prepare('SELECT id FROM products ORDER BY id DESC LIMIT 1').get();
    if (newProduct) {
      const affUrl = buildAffUrl(buy_url, aff_code, aff_param);
      db.prepare('INSERT INTO aff_links (product_id, platform, url, notes) VALUES (?, ?, ?, ?)')
        .run(newProduct.id, 'default', affUrl, '自动生成');
    }
  }

  res.redirect('/admin/products');
});

// 编辑页面
router.get('/:id/edit', (req, res) => {
  const product = db.prepare('SELECT * FROM products WHERE id = ?').get(req.params.id);
  if (!product) return res.redirect('/admin/products');
  const merchants = db.prepare('SELECT id, name FROM merchants ORDER BY name').all();

  // 计算生成的 aff 链接用于展示
  product.generated_aff_url = (product.aff_code && product.buy_url)
    ? buildAffUrl(product.buy_url, product.aff_code, product.aff_param || 'aff')
    : null;

  res.render('admin/product-edit', { product, merchants });
});

// 保存编辑
router.post('/:id/edit', (req, res) => {
  const {
    merchant_id, name, url, buy_url, sku, price, annual_price, location,
    spec_summary, traffic, billing_cycle, coupon_code, tags, push_intro, notes,
    check_mode, in_stock_keywords, out_of_stock_keywords,
    is_public, is_featured, sort_order
  } = req.body;

  if (!name || !merchant_id) return res.redirect(`/admin/products/${req.params.id}/edit`);

  // 获取当前产品的 internal_pid（保留已有值）
  const existing = db.prepare('SELECT internal_pid, aff_code, aff_param FROM products WHERE id = ?').get(req.params.id);

  // 自动填充 PID 字段
  const pidFields = autoFillPidFields(db, {
    internal_pid: (existing && existing.internal_pid) || null,
    slug: req.body.slug || null,
    provider_pid: req.body.provider_pid || null,
    name,
    merchant_id,
    buy_url,
    url,
    id: parseInt(req.params.id, 10),
  });

  // 处理 aff_code
  let aff_code = req.body.aff_code || null;
  let aff_param = req.body.aff_param || 'aff';
  if (!aff_code && buy_url) {
    const parsed = parseAffCode(buy_url);
    if (parsed) {
      aff_code = parsed.value;
      aff_param = parsed.param;
    }
  }

  // 计算生成的 aff 链接
  const generated_aff_url = (aff_code && buy_url)
    ? buildAffUrl(buy_url, aff_code, aff_param)
    : null;

  db.prepare(`
    UPDATE products SET
      merchant_id = ?, name = ?, url = ?, buy_url = ?, sku = ?, price = ?,
      annual_price = ?, location = ?, spec_summary = ?, traffic = ?,
      billing_cycle = ?, coupon_code = ?, tags = ?, push_intro = ?, notes = ?,
      check_mode = ?, in_stock_keywords = ?, out_of_stock_keywords = ?,
      is_public = ?, is_featured = ?, sort_order = ?,
      internal_pid = ?, provider_pid = ?, slug = ?,
      aff_code = ?, aff_param = ?, generated_aff_url = ?,
      updated_at = datetime('now')
    WHERE id = ?
  `).run(
    merchant_id,
    name,
    url || null,
    buy_url || null,
    sku || null,
    price || null,
    annual_price || null,
    location || null,
    spec_summary || null,
    traffic || null,
    billing_cycle || null,
    coupon_code || null,
    tags || null,
    push_intro || null,
    notes || null,
    check_mode || 'keyword',
    in_stock_keywords || null,
    out_of_stock_keywords || null,
    is_public ? 1 : 0,
    is_featured ? 1 : 0,
    parseInt(sort_order, 10) || 100,
    pidFields.internal_pid,
    pidFields.provider_pid || null,
    pidFields.slug,
    aff_code || null,
    aff_param || 'aff',
    generated_aff_url,
    req.params.id
  );

  res.redirect('/admin/products');
});

// API: 从 URL 解析 provider_pid（前端 AJAX 用）
router.get('/api/parse-pid', (req, res) => {
  const { url } = req.query;
  const pid = parseProviderPid(url);
  const aff = parseAffCode(url);
  res.json({
    provider_pid: pid,
    aff_code: aff ? aff.value : null,
    aff_param: aff ? aff.param : null,
  });
});

// API: 生成 aff 链接预览
router.get('/api/build-aff-url', (req, res) => {
  const { base_url, aff_code, aff_param } = req.query;
  if (!base_url || !aff_code) {
    return res.json({ aff_url: null });
  }
  const affUrl = buildAffUrl(base_url, aff_code, aff_param || 'aff');
  res.json({ aff_url: affUrl });
});

// 删除
router.post('/:id/delete', (req, res) => {
  db.prepare('DELETE FROM products WHERE id = ?').run(req.params.id);
  res.redirect('/admin/products');
});

module.exports = router;
