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

router.get('/', (req, res) => {
  const links = db.prepare(`
    SELECT a.*, p.name AS product_name, m.name AS merchant_name, p.generated_aff_url
    FROM aff_links a
    LEFT JOIN products p ON a.product_id = p.id
    LEFT JOIN merchants m ON p.merchant_id = m.id
    ORDER BY a.id DESC
  `).all();
  const products = db.prepare(`
    SELECT p.id, p.name, p.buy_url, p.url, p.aff_code, p.aff_param, p.generated_aff_url, m.name AS merchant_name
    FROM products p LEFT JOIN merchants m ON p.merchant_id = m.id
    ORDER BY m.name, p.name
  `).all();
  res.render('admin/affLinks', { links, products });
});

router.post('/', (req, res) => {
  const { product_id, platform, url, notes } = req.body;
  if (!product_id) return res.redirect('/admin/aff-links');

  let finalUrl = url;

  // 如果没有手填链接，尝试从产品的 buy_url + aff_code 自动生成
  if (!finalUrl || !finalUrl.trim()) {
    const product = db.prepare('SELECT buy_url, url, aff_code, aff_param FROM products WHERE id = ?').get(product_id);
    if (product && product.aff_code) {
      const baseUrl = product.buy_url || product.url;
      if (baseUrl) {
        finalUrl = buildAffUrl(baseUrl, product.aff_code, product.aff_param || 'aff');
      }
    }
  }

  if (!finalUrl) return res.redirect('/admin/aff-links');

  db.prepare('INSERT INTO aff_links (product_id, platform, url, notes) VALUES (?, ?, ?, ?)')
    .run(product_id, platform || 'default', finalUrl, notes || null);
  res.redirect('/admin/aff-links');
});

// 批量为所有有 aff_code 但没有 aff_link 的产品生成
router.post('/generate-all', (req, res) => {
  const products = db.prepare(`
    SELECT p.id, p.buy_url, p.url, p.aff_code, p.aff_param
    FROM products p
    WHERE p.aff_code IS NOT NULL AND p.aff_code != ''
      AND p.id NOT IN (SELECT DISTINCT product_id FROM aff_links)
  `).all();

  let count = 0;
  const insert = db.prepare('INSERT INTO aff_links (product_id, platform, url, notes) VALUES (?, ?, ?, ?)');
  db.transaction(() => {
    for (const p of products) {
      const baseUrl = p.buy_url || p.url;
      if (!baseUrl) continue;
      const affUrl = buildAffUrl(baseUrl, p.aff_code, p.aff_param || 'aff');
      insert.run(p.id, 'default', affUrl, '批量自动生成');
      count++;
    }
  })();

  res.redirect('/admin/aff-links');
});

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

module.exports = router;
