/**
 * 省胜优铺 · 授权管理 API（前端后台菜单调用）
 * ============================================
 * GET  /api/ssyp-license/info        查询当前授权状态
 * POST /api/ssyp-license/activate    激活授权码（对接独立授权服务器）
 * GET  /api/ssyp-license/branding    获取当前应显示的版权信息
 * ============================================
 */
const express = require('express');
const router = express.Router();
const ssyp = require('../lib/ssyp-license');
const heartbeat = require('../lib/license-heartbeat');

// 手动触发一次在线复查（退款撤销锁定检查）
router.post('/check-revoke', async (req, res) => {
  try {
    const result = await heartbeat.checkOnce();
    res.json({ code: 0, message: '复查完成', data: result });
  } catch (e) {
    res.json({ code: 1, message: '复查失败: ' + e.message, data: null });
  }
});

// 查询当前授权状态
router.get('/info', (req, res) => {
  try {
    const lic = ssyp.getLocalLicense();
    res.json({
      code: 0,
      message: 'ok',
      data: {
        type: lic.type,                 // free / branded_199 / unbranded_599
        activated: lic.activated,
        domain: lic.domain || '',
        machineId: lic.machineId,
        machineIdShort: lic.machineId ? lic.machineId.substring(0, 8) + '...' : '',
        // 展示文案
        typeText: {
          free: '免费版',
          branded_199: '199元·永久授权（保留版权）',
          unbranded_599: '599元·永久授权（去除版权）',
        }[lic.type] || '免费版',
      },
    });
  } catch (e) {
    res.json({ code: 1, message: '查询授权状态失败: ' + e.message, data: null });
  }
});

// 激活授权码
router.post('/activate', async (req, res) => {
  try {
    const { licenseCode, domain } = req.body || {};
    if (!licenseCode || !domain) {
      return res.json({ code: 1, message: '请填写授权码和绑定域名' });
    }
    const result = await ssyp.activateLicense(licenseCode, domain);
    if (!result.ok) {
      return res.json({ code: 1, message: result.message });
    }
    res.json({ code: 0, message: result.message, data: result.license });
  } catch (e) {
    res.json({ code: 1, message: '激活失败: ' + e.message });
  }
});

// 获取当前版权信息（前端/后端渲染用）
router.get('/branding', (req, res) => {
  try {
    const lic = ssyp.getLocalLicense();
    res.json({
      code: 0,
      message: 'ok',
      data: {
        showBrand: lic.type !== 'unbranded_599',   // 599 去版权则不显示
        html: ssyp.getBranding(),
        brand: ssyp.BRAND,
      },
    });
  } catch (e) {
    res.json({ code: 1, message: '获取版权信息失败: ' + e.message, data: null });
  }
});

module.exports = router;
