/**
 * 后台设置页 — TG Bot Token / 默认频道等
 */
const router = require('express').Router();
const db = require('../db');
const { getSetting, setSetting, getAllSettings, maskToken } = require('../utils/settings');
const { sendTestMessage } = require('../utils/telegram');

// 设置页
router.get('/', (req, res) => {
  const settings = getAllSettings();

  // 准备展示数据
  const formData = {
    TG_BOT_TOKEN: settings.TG_BOT_TOKEN || '',
    TG_BOT_TOKEN_MASKED: settings.TG_BOT_TOKEN ? maskToken(settings.TG_BOT_TOKEN) : '',
    TG_DEFAULT_CHANNEL_ID: settings.TG_DEFAULT_CHANNEL_ID || '',
    SITE_NAME: settings.SITE_NAME || process.env.SITE_NAME || 'VPS补货监控',
    SITE_TG_URL: settings.SITE_TG_URL || '',
    DEFAULT_AFF_CODE: settings.DEFAULT_AFF_CODE || '',
  };

  res.render('admin/settings', { formData, flash: req.query.flash || null });
});

// 保存设置
router.post('/', (req, res) => {
  const { TG_BOT_TOKEN, TG_DEFAULT_CHANNEL_ID, SITE_NAME, SITE_TG_URL, DEFAULT_AFF_CODE } = req.body;

  // 只有填了值才更新（空字符串也更新，表示清空）
  if (TG_BOT_TOKEN !== undefined) {
    setSetting('TG_BOT_TOKEN', TG_BOT_TOKEN.trim());
  }
  if (TG_DEFAULT_CHANNEL_ID !== undefined) {
    setSetting('TG_DEFAULT_CHANNEL_ID', TG_DEFAULT_CHANNEL_ID.trim());
  }
  if (SITE_NAME !== undefined) {
    setSetting('SITE_NAME', SITE_NAME.trim());
  }
  if (SITE_TG_URL !== undefined) {
    setSetting('SITE_TG_URL', SITE_TG_URL.trim());
  }
  if (DEFAULT_AFF_CODE !== undefined) {
    setSetting('DEFAULT_AFF_CODE', DEFAULT_AFF_CODE.trim());
  }

  res.redirect('/admin/settings?flash=' + encodeURIComponent('✅ 设置已保存'));
});

// 测试 Telegram 连接
router.post('/test-telegram', async (req, res) => {
  const { chat_id } = req.body;

  // 动态获取最新的 token（DB 优先）
  const token = getSetting('TG_BOT_TOKEN');
  const defaultChannel = getSetting('TG_DEFAULT_CHANNEL_ID');

  if (!token) {
    return res.redirect('/admin/settings?flash=' + encodeURIComponent('❌ 未配置 TG_BOT_TOKEN'));
  }

  const targetChatId = chat_id || defaultChannel;
  if (!targetChatId) {
    return res.redirect('/admin/settings?flash=' + encodeURIComponent('❌ 未指定测试频道且无默认频道'));
  }

  // 发送测试消息
  const result = await sendTestMessage(targetChatId);

  const msg = result.ok
    ? encodeURIComponent(`✅ 测试成功！已发送到 ${targetChatId}`)
    : encodeURIComponent(`❌ 测试失败: ${result.description}`);
  res.redirect(`/admin/settings?flash=${msg}`);
});

// 获取 Bot 信息（API）
router.get('/api/bot-info', async (req, res) => {
  const token = getSetting('TG_BOT_TOKEN');
  if (!token) {
    return res.json({ ok: false, error: '未配置 TG_BOT_TOKEN' });
  }

  try {
    const fetchRes = await fetch(`https://api.telegram.org/bot${token}/getMe`);
    const data = await fetchRes.json();
    res.json(data);
  } catch (err) {
    res.json({ ok: false, error: err.message });
  }
});

module.exports = router;
