/**
 * 通知管理 - API 路由
 */
const express = require('express');
const router = express.Router();
const { get, run, all } = require('../utils/db');
const { success, fail, page } = require('../utils/response');
const { authUser, authAdmin } = require('../middleware/auth');
const notification = require('../lib/notification');
const { getAllTemplates } = require('../lib/notification/templates');
const { isFeatureEnabled } = require('../lib/license');

// ========== 功能门控：消息推送仅在完整版可用 ==========
router.use((req, res, next) => {
  if (!isFeatureEnabled('notification')) {
    return res.json(fail('当前版本不支持消息推送功能', 403));
  }
  next();
});

// ===================================================================
// 1. 管理员手动发送通知 - POST /api/notification/send
// ===================================================================
router.post('/send', authAdmin, async (req, res) => {
  try {
    const { template_code, user_id, params, channel } = req.body;
    if (!template_code || !user_id) {
      return res.json(fail('缺少必要参数: template_code, user_id'));
    }

    const result = await notification.send(template_code, user_id, params || {}, {
      channel: channel || null,
      force: true
    });

    if (result.success) {
      return res.json(success(result, '发送成功'));
    } else {
      const errors = result.results.map(r => r.error).filter(Boolean).join('; ');
      return res.json(fail(errors || '发送失败'));
    }
  } catch (e) {
    console.error('[通知] 发送失败:', e);
    return res.json(fail('发送失败: ' + e.message));
  }
});

// ===================================================================
// 2. 模板列表 - GET /api/notification/templates
// ===================================================================
router.get('/templates', authAdmin, (req, res) => {
  // 优先从数据库查，数据库没有时使用内置定义
  const dbTemplates = all('SELECT * FROM notification_templates ORDER BY code ASC');
  if (dbTemplates.length > 0) {
    return res.json(success(dbTemplates));
  }
  // 兜底返回内置模板（只包含基本信息）
  const builtin = getAllTemplates().map(t => ({
    code: t.code,
    type: t.type,
    title: t.title,
    content: t.content,
    variables: JSON.stringify(t.variables),
    channels: JSON.stringify(t.channels),
    status: 1
  }));
  return res.json(success(builtin));
});

// ===================================================================
// 3. 发送日志 - GET /api/notification/logs
// ===================================================================
router.get('/logs', authAdmin, (req, res) => {
  const { page: p = 1, pageSize = 20, status: filterStatus, user_id, template_code } = req.query;
  const pageNum = Math.max(1, +p);
  const size = Math.min(100, Math.max(1, +pageSize));

  let where = 'WHERE 1=1';
  const params = [];
  if (filterStatus) { where += ' AND status=?'; params.push(filterStatus); }
  if (user_id) { where += ' AND user_id=?'; params.push(+user_id); }
  if (template_code) { where += ' AND template_code=?'; params.push(template_code); }

  const total = get(`SELECT COUNT(*) as c FROM notification_logs ${where}`, params).c;
  const list = all(
    `SELECT nl.*, u.nickname, u.phone
     FROM notification_logs nl
     LEFT JOIN users u ON nl.user_id=u.id
     ${where}
     ORDER BY nl.id DESC
     LIMIT ? OFFSET ?`,
    [...params, size, (pageNum - 1) * size]
  );

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

// ===================================================================
// 4. 用户订阅设置 - GET /api/notification/prefs
// ===================================================================
router.get('/prefs', authUser, (req, res) => {
  const prefs = all('SELECT * FROM user_notification_prefs WHERE user_id=?', [req.userId]);
  return res.json(success(prefs));
});

// ===================================================================
// 5. 更新订阅设置 - PUT /api/notification/prefs
// ===================================================================
router.put('/prefs', authUser, (req, res) => {
  try {
    const { template_code, channels, enabled } = req.body;
    if (!template_code) return res.json(fail('template_code 必填'));

    const existing = get('SELECT id FROM user_notification_prefs WHERE user_id=? AND template_code=?', [req.userId, template_code]);

    if (existing) {
      run(
        'UPDATE user_notification_prefs SET channels=?, enabled=?, updated_at=datetime(\'now\',\'localtime\') WHERE id=?',
        [JSON.stringify(channels || []), enabled !== false ? 1 : 0, existing.id]
      );
    } else {
      run(
        'INSERT INTO user_notification_prefs(user_id, template_code, channels, enabled) VALUES(?,?,?,?)',
        [req.userId, template_code, JSON.stringify(channels || []), enabled !== false ? 1 : 0]
      );
    }

    return res.json(success(null, '更新成功'));
  } catch (e) {
    return res.json(fail('更新失败: ' + e.message));
  }
});

module.exports = router;
