/**
 * LiteMall AI 内容审核路由
 * 
 * 功能：
 * - 列出待审核/已审核的 AI 生成内容
 * - 审核通过/驳回操作（记录操作人、时间、理由）
 * - 查询审核日志
 * 
 * 设计依据：
 * - 软著审查要求「AI生成内容必须有人工干预节点」
 * - 《网络反不正当竞争暂行规定》第12条禁止批量生成虚假评价
 * - 审核操作日志留存，用于「人工创新」举证材料
 * 
 * 流程图：
 *   AI生成 → 存入待审池(status: pending_review) → 运营审核 → 
 *   [通过: status=approved + 记录审核人] / [驳回: status=rejected + 驳回理由]
 * 
 * 创建时间：2026-06-21
 */

const express = require('express');
const router = express.Router();
const { get, run, all } = require('../utils/db');
const { success, fail, page } = require('../utils/response');
const { authAdmin } = require('../middleware/auth');

// ==================== 中间件：管理员认证 ====================
router.use(authAdmin);

/**
 * 保存 AI 生成内容到审核表
 * 
 * @param {Object} params
 * @param {string} params.sourceType - 来源类型
 * @param {number} params.sourceId - 关联ID（如商品ID）
 * @param {string} params.sourceName - 来源名称（如商品名）
 * @param {string} params.content - AI生成的内容
 * @param {string} params.requestInput - 原始请求输入
 * @param {number} params.adminId - 生成该内容的管理员ID
 * @returns {number} 审核记录ID
 */
function saveToReview(params) {
  const { sourceType, sourceId, sourceName, content, requestInput, adminId } = params;
  const result = run(
    `INSERT INTO ai_content_reviews(source_type, source_id, source_name, content, request_input, admin_id)
     VALUES(?, ?, ?, ?, ?, ?)`,
    [sourceType, sourceId || 0, sourceName || '', content, requestInput || '', adminId]
  );
  return result.lastInsertRowid;
}

/**
 * 获取审核列表
 * GET /api/ai-review/list
 * Query: status (pending_review|approved|rejected), source_type, page, pageSize
 */
router.get('/list', (req, res) => {
  const status = req.query.status || '';
  const sourceType = req.query.source_type || '';
  const pageNum = parseInt(req.query.page) || 1;
  const pageSize = parseInt(req.query.pageSize) || 20;
  const offset = (pageNum - 1) * pageSize;

  let where = 'WHERE 1=1';
  const params = [];

  if (status) {
    where += ' AND acr.status=?';
    params.push(status);
  }
  if (sourceType) {
    where += ' AND acr.source_type=?';
    params.push(sourceType);
  }

  const countSql = `SELECT COUNT(*) as c FROM ai_content_reviews acr ${where}`;
  const countResult = get(countSql, params);
  const total = countResult ? countResult.c : 0;

  const listSql = `
    SELECT acr.*, u.nickname as admin_name
    FROM ai_content_reviews acr
    LEFT JOIN users u ON acr.admin_id=u.id
    ${where}
    ORDER BY acr.created_at DESC
    LIMIT ? OFFSET ?
  `;
  const list = all(listSql, [...params, pageSize, offset]);

  return res.json(success(page(list, total, pageNum, pageSize)));
});

/**
 * 审核通过
 * POST /api/ai-review/approve/:id
 * Body: { comment }
 */
router.post('/approve/:id', (req, res) => {
  const id = parseInt(req.params.id);
  const comment = req.body.comment || '';

  const review = get('SELECT * FROM ai_content_reviews WHERE id=?', [id]);
  if (!review) return res.json(fail('审核记录不存在'));
  if (review.status !== 'pending_review') return res.json(fail('该内容已被审核，不可重复操作'));

  run(
    `UPDATE ai_content_reviews SET status='approved', review_comment=?, reviewed_by=?, reviewed_at=datetime('now','localtime') WHERE id=?`,
    [comment, req.userId, id]
  );

  // 记录审核日志到操作日志
  run(
    `INSERT INTO operation_logs(admin_id, action, module, target_id, detail) VALUES(?, ?, ?, ?, ?)`,
    [req.userId, 'ai_review_approve', 'ai_content', id, `审核通过 AI 生成${review.source_type}内容: ${review.source_name}`]
  );

  return res.json(success(null, '已审核通过'));
});

/**
 * 审核驳回
 * POST /api/ai-review/reject/:id
 * Body: { reason (必填) }
 */
router.post('/reject/:id', (req, res) => {
  const id = parseInt(req.params.id);
  const reason = req.body.reason || '';

  if (!reason) return res.json(fail('驳回必须填写理由'));

  const review = get('SELECT * FROM ai_content_reviews WHERE id=?', [id]);
  if (!review) return res.json(fail('审核记录不存在'));
  if (review.status !== 'pending_review') return res.json(fail('该内容已被审核，不可重复操作'));

  run(
    `UPDATE ai_content_reviews SET status='rejected', review_comment=?, reviewed_by=?, reviewed_at=datetime('now','localtime') WHERE id=?`,
    [reason, req.userId, id]
  );

  run(
    `INSERT INTO operation_logs(admin_id, action, module, target_id, detail) VALUES(?, ?, ?, ?, ?)`,
    [req.userId, 'ai_review_reject', 'ai_content', id, `驳回 AI 生成${review.source_type}内容: ${review.source_name}，理由: ${reason}`]
  );

  return res.json(success(null, '已驳回'));
});

/**
 * 审核统计概览
 * GET /api/ai-review/stats
 */
router.get('/stats', (req, res) => {
  const total = get("SELECT COUNT(*) as c FROM ai_content_reviews");
  const pending = get("SELECT COUNT(*) as c FROM ai_content_reviews WHERE status='pending_review'");
  const approved = get("SELECT COUNT(*) as c FROM ai_content_reviews WHERE status='approved'");
  const rejected = get("SELECT COUNT(*) as c FROM ai_content_reviews WHERE status='rejected'");

  return res.json(success({
    total: total ? total.c : 0,
    pending: pending ? pending.c : 0,
    approved: approved ? approved.c : 0,
    rejected: rejected ? rejected.c : 0,
  }));
});

// 导出 saveToReview 供其他路由模块使用
router.saveToReview = saveToReview;

module.exports = router;
