/**
 * LiteMall 授权管理 API 路由
 * 
 * 功能：
 * - 获取授权信息（版本、功能清单）
 * - 完整性校验报告
 * - 更新授权配置
 * - 授权码激活（绑定域名+机器码）
 */

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');
const license = require('../lib/license');
const crypto = require('crypto');

// ==================== 公共接口（无需登录） ====================

/**
 * 获取版本简要信息
 * GET /api/license/version
 */
router.get('/version', (req, res) => {
  const licenseType = license.getLicenseType();
  const isFree = licenseType === license.LICENSE_TYPES.FREE;
  
  return res.json(success({
    version: '1.0.0',
    license_type: licenseType,
    edition: isFree ? '免费版' : '完整版',
    powered_by: 'LiteMall 轻商城',
    system_id: license.getSystemId().substring(0, 8) + '****'
  }));
});

// ==================== 管理接口（需管理员登录） ====================

/**
 * 获取完整授权信息
 * GET /api/license/info
 */
router.get('/info', authAdmin, (req, res) => {
  const licenseType = license.getLicenseType();
  const featureList = license.getFeatureList();
  const validation = license.validateLicense();
  
  // 读取配置
  const boundDomain = get("SELECT value FROM system_config WHERE key='license_bound_domain'")?.value || '';
  const integrityStatus = get("SELECT value FROM system_config WHERE key='integrity_check'")?.value || 'unknown';
  
  return res.json(success({
    // 版本信息
    license_type: licenseType,
    edition: licenseType === 'free' ? '免费版' : '完整版',
    
    // 授权验证
    validation: {
      valid: validation.valid,
      message: validation.message,
    },
    
    // 绑定信息
    system_id: license.getSystemId(),
    bound_domain: boundDomain,
    
    // 功能清单
    features: featureList,
    
    // 安全状态
    integrity_status: integrityStatus,
    
    // 配置项
    has_custom_copyright: !!get("SELECT value FROM system_config WHERE key='copyright_text'")?.value,
  }));
});

/**
 * 获取完整性校验报告
 * GET /api/license/integrity
 */
router.get('/integrity', authAdmin, (req, res) => {
  const report = license.checkTamper();
  
  // 统计
  const total = report.length;
  const pass = report.filter(r => r.status === 'pass').length;
  const tampered = report.filter(r => r.status === 'tampered').length;
  const unrecorded = report.filter(r => r.status === 'unrecorded').length;
  
  return res.json(success({
    summary: {
      total,
      pass,
      tampered,
      unrecorded,
      safe: tampered === 0,
    },
    files: report,
    check_time: new Date().toISOString(),
  }));
});

/**
 * 更新授权配置
 * POST /api/license/config
 * Body: { license_type, license_key, bound_domain, copyright_text }
 */
router.post('/config', authAdmin, (req, res) => {
  try {
    const { license_type, license_key, bound_domain, copyright_text } = req.body;
    
    if (license_type) {
      const validTypes = Object.values(license.LICENSE_TYPES);
      if (!validTypes.includes(license_type)) {
        return res.json(fail('无效的授权类型'));
      }
      run("UPDATE system_config SET value=? WHERE key='license_type'", [license_type]);
    }
    
    if (license_key !== undefined) {
      run("UPDATE system_config SET value=? WHERE key='license_key'", [license_key]);
    }
    
    if (bound_domain !== undefined) {
      run("UPDATE system_config SET value=? WHERE key='license_bound_domain'", [bound_domain]);
    }
    
    if (copyright_text !== undefined) {
      run("UPDATE system_config SET value=? WHERE key='copyright_text'", [copyright_text]);
    }
    
    // 更新完整性校验
    try {
      license.initFileHashes();
    } catch (e) {
      // ignore
    }
    
    return res.json(success(null, '授权配置更新成功'));
  } catch (e) {
    return res.json(fail('更新失败: ' + e.message));
  }
});

module.exports = router;

/**
 * 激活授权码
 * POST /api/license/activate
 * Body: { license_key: string }
 * 
 * 流程:
 *   1. 用 license_key + 系统机器码 + 域名 组合校验
 *   2. 校验通过 → 更新 license_type + license_key + bound_domain
 *   3. 校验失败 → 返回错误信息，保持免费版
 */
router.post('/activate', (req, res) => {
  // 🔒 资金安全：旧版本地激活算法含硬编码万能码/可逆salt（授权绕过后门），已彻底移除。
  // 授权激活统一走独立、安全的 ssyp-license 体系（/api/ssyp-license/activate）。
  return res.status(403).json(fail('旧版激活接口已禁用，请使用授权管理激活', 403));
});


router.get('/activation-info', (req, res) => {
  const systemId = license.getSystemId();
  const currentDomain = req.headers['host'] || req.get('host') || '';
  const domain = currentDomain.split(':')[0];

  return res.json(success({
    system_id: systemId,
    current_domain: domain,
    license_type: license.getLicenseType(),
    edition: license.getLicenseType() === 'free' ? '免费版' : '完整版',
  }));
});

/**
 * 切换回免费版（降级）
 * POST /api/license/downgrade
 */
router.post('/downgrade', authAdmin, (req, res) => {
  run("UPDATE system_config SET value=? WHERE key='license_type'", [license.LICENSE_TYPES.FREE]);
  run("UPDATE system_config SET value=? WHERE key='license_key'", ['']);
  return res.json(success(null, '已降级为免费版'));
});

module.exports = router;
