/**
 * LiteMall 自动 SEO 文章生成器 · 后台管理 API
 * 路径前缀 /api/admin/seo
 * 鉴权：全部 authAdmin
 */

const express = require('express');
const router = express.Router();
const { get, all, run } = require('../utils/db');
const generator = require('../lib/seo-article-generator');
const scheduler = require('../jobs/seo-scheduler');

const { success, fail } = require('../utils/response');
const { authAdmin } = require('../middleware/auth');
router.use(authAdmin);

// ========== 任务 CRUD ==========
router.get('/tasks', (req, res) => {
  const list = all('SELECT * FROM seo_article_tasks ORDER BY id DESC');
  // 附带最近一次生成日志
  const withLog = list.map(t => {
    const last = get('SELECT * FROM seo_generate_logs WHERE task_id=? ORDER BY id DESC LIMIT 1', [t.id]);
    return { ...t, last_log: last || null };
  });
  res.json(success(withLog));
});

router.post('/tasks', (req, res) => {
  const b = req.body || {};
  const name = String(b.name || '').trim();
  if (!name) return res.json(fail('请填写任务名称'));
  const r = run(
    'INSERT INTO seo_article_tasks(name,enabled,generate_time,daily_count,mode,category_id,max_price,keyword_source,article_status) VALUES(?,?,?,?,?,?,?,?,?)',
    [name, b.enabled === 0 ? 0 : 1, b.generate_time || '06:30', b.daily_count || 1,
     ['spec','qa','scene','compare','random'].includes(b.mode) ? b.mode : 'random',
     b.category_id || 0, b.max_price || 0, b.keyword_source || 'combo', b.article_status === 1 ? 1 : 0]
  );
  res.json(success({ id: r.lastInsertRowid }, '任务已创建'));
});

router.put('/tasks/:id', (req, res) => {
  const id = Number(req.params.id);
  const t = get('SELECT * FROM seo_article_tasks WHERE id=?', [id]);
  if (!t) return res.json(fail('任务不存在'));
  const b = req.body || {};
  run("UPDATE seo_article_tasks SET name=?,enabled=?,generate_time=?,daily_count=?,mode=?,category_id=?,max_price=?,keyword_source=?,article_status=?,updated_at=datetime('now','localtime') WHERE id=?",
    [String(b.name || t.name).trim(), b.enabled === undefined ? t.enabled : (b.enabled ? 1 : 0),
     b.generate_time || t.generate_time, b.daily_count || t.daily_count,
     ['spec','qa','scene','compare','random'].includes(b.mode) ? b.mode : t.mode,
     b.category_id !== undefined ? b.category_id : t.category_id,
     b.max_price !== undefined ? b.max_price : t.max_price,
     b.keyword_source || t.keyword_source,
     b.article_status === 1 ? 1 : 0, id]);
  res.json(success(null,'已更新'));
});

router.delete('/tasks/:id', (req, res) => {
  run('DELETE FROM seo_article_tasks WHERE id=?', [req.params.id]);
  res.json(success(null,'已删除'));
});

// 手动立即生成（测试）
router.post('/tasks/:id/run', async (req, res) => {
  try {
    const result = await scheduler.runTaskNow(Number(req.params.id));
    res.json(success(result, result.skip ? '无可生成商品或今日已全部生成' : `成功生成 ${result.gen}/${result.total} 篇`));
  } catch (e) {
    res.json(fail(e.message || '生成失败'));
  }
});

// ========== 商品列表（任务可选范围） ==========
router.get('/products', (req, res) => {
  const list = all('SELECT p.id, p.name, p.price, c.name as category_name FROM products p LEFT JOIN categories c ON p.category_id=c.id WHERE p.status=1 ORDER BY p.id LIMIT 500');
  res.json(success(list));
});
router.get('/categories', (req, res) => {
  res.json(success(all('SELECT * FROM categories ORDER BY id')));
});

// ========== 搜索长尾词 ==========
router.get('/keywords', (req, res) => {
  res.json(success(all('SELECT keyword, count, last_seen FROM search_keywords ORDER BY count DESC, id DESC LIMIT 100')));
});
router.delete('/keywords/:id', (req, res) => {
  run('DELETE FROM search_keywords WHERE id=?', [req.params.id]);
  res.json(success(null,'已删除'));
});

// ========== 生成日志 ==========
router.get('/logs', (req, res) => {
  const list = all('SELECT * FROM seo_generate_logs ORDER BY id DESC LIMIT 100');
  res.json(success(list));
});

// ========== 试运行：预览一篇生成结果（不落库） ==========
router.post('/preview', async (req, res) => {
  try {
    const b = req.body || {};
    const productId = Number(b.product_id);
    const product = get('SELECT p.*, c.name as category_name FROM products p LEFT JOIN categories c ON p.category_id=c.id WHERE p.id=?', [productId]);
    if (!product) return res.json(fail('商品不存在'));
    const task = {
      mode: b.mode || 'random',
      keyword_source: b.keyword_source || 'combo',
      category_id: 0,
      max_price: 0,
    };
    const article = await generator.generateArticle(product, task);
    res.json(success(article));
  } catch (e) {
    res.json(fail(e.message || '生成失败'));
  }
});

// ========== 配置信息（AI 是否已配置） ==========
router.get('/config', (req, res) => {
  const { getAiConfig } = require('../lib/ai-client');
  const cfg = getAiConfig();
  res.json(success({ ai_configured: !!cfg.apiKey, ai_model: cfg.model || '', hint: cfg.apiKey ? '' : '请先在 AI 配置中填写 API Key' }));
});

module.exports = router;
