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 { isFeatureEnabled } = require('../lib/license');

// ========== 付费版权限检查中间件 ==========
router.use(authAdmin, (req, res, next) => {
  if (!isFeatureEnabled('page_designer')) {
    return res.json({ code: 403, message: '当前版本不支持APP管理功能，请升级完整版' });
  }
  next();
});

// ========== APP基础配置 ==========

// 获取APP配置
router.get('/config', (req, res) => {
  try {
    let config = get('SELECT * FROM app_config WHERE id=1');
    if (!config) {
      run('INSERT INTO app_config (id) VALUES (1)');
      config = get('SELECT * FROM app_config WHERE id=1');
    }
    if (config.bottom_nav) {
      try { config.bottom_nav = JSON.parse(config.bottom_nav); } catch(e) { config.bottom_nav = []; }
    }
    return res.json(success(config));
  } catch (e) {
    return res.json(fail('获取APP配置失败'));
  }
});

// 保存APP配置
router.put('/config', (req, res) => {
  try {
    const { splash_image, splash_link, ad_image, ad_link, ad_duration, bottom_nav } = req.body;
    const exist = get('SELECT id FROM app_config WHERE id=1');
    const navStr = JSON.stringify(bottom_nav || []);
    if (exist) {
      run("UPDATE app_config SET splash_image=?, splash_link=?, ad_image=?, ad_link=?, ad_duration=?, bottom_nav=?, updated_at=datetime('now','localtime') WHERE id=1",
        [splash_image || '', splash_link || '', ad_image || '', ad_link || '', ad_duration || 3, navStr]);
    } else {
      run('INSERT INTO app_config (splash_image, splash_link, ad_image, ad_link, ad_duration, bottom_nav) VALUES (?,?,?,?,?,?)',
        [splash_image || '', splash_link || '', ad_image || '', ad_link || '', ad_duration || 3, navStr]);
    }
    return res.json(success(null, '保存成功'));
  } catch (e) {
    return res.json(fail('保存APP配置失败'));
  }
});

// ========== APP版本管理 ==========

// 版本列表（分页）
router.get('/versions', (req, res) => {
  try {
    const pageNum = Math.max(1, parseInt(req.query.page) || 1);
    const size = Math.min(100, Math.max(1, parseInt(req.query.pageSize) || 20));
    const total = get('SELECT COUNT(*) as c FROM app_versions').c;
    const list = all('SELECT * FROM app_versions ORDER BY id DESC LIMIT ? OFFSET ?', [size, (pageNum - 1) * size]);
    return res.json(page(list, total, pageNum, size));
  } catch (e) {
    return res.json(fail('获取版本列表失败'));
  }
});

// 新增版本
router.post('/versions', (req, res) => {
  try {
    const { version_name, version_code, update_log, download_url, force_update, platform } = req.body;
    if (!version_name) return res.json(fail('版本名不能为空'));
    if (!version_code) return res.json(fail('版本号不能为空'));
    const r = run('INSERT INTO app_versions (version_name, version_code, update_log, download_url, force_update, platform) VALUES (?,?,?,?,?,?)',
      [version_name, version_code, update_log || '', download_url || '', force_update ? 1 : 0, platform || 'all']);
    return res.json(success({ id: r.lastInsertRowid }, '添加成功'));
  } catch (e) {
    return res.json(fail('添加版本失败'));
  }
});

// 更新版本
router.put('/versions/:id', (req, res) => {
  try {
    const { version_name, version_code, update_log, download_url, force_update, platform, status } = req.body;
    const exist = get('SELECT id FROM app_versions WHERE id=?', [req.params.id]);
    if (!exist) return res.json(fail('版本不存在'));
    run('UPDATE app_versions SET version_name=?, version_code=?, update_log=?, download_url=?, force_update=?, platform=?, status=? WHERE id=?',
      [version_name, version_code, update_log || '', download_url || '', force_update ? 1 : 0, platform || 'all', status || 1, req.params.id]);
    return res.json(success(null, '更新成功'));
  } catch (e) {
    return res.json(fail('更新版本失败'));
  }
});

// 删除版本
router.delete('/versions/:id', (req, res) => {
  try {
    const exist = get('SELECT id FROM app_versions WHERE id=?', [req.params.id]);
    if (!exist) return res.json(fail('版本不存在'));
    run('DELETE FROM app_versions WHERE id=?', [req.params.id]);
    return res.json(success(null, '删除成功'));
  } catch (e) {
    return res.json(fail('删除版本失败'));
  }
});

// 客户端检查更新（公开接口，无auth）
router.get('/version/latest', (req, res) => {
  try {
    const latest = get("SELECT * FROM app_versions WHERE status=1 ORDER BY version_code DESC LIMIT 1");
    if (!latest) {
      return res.json(success(null, '没有新版本'));
    }
    return res.json(success(latest));
  } catch (e) {
    return res.json(fail('获取最新版本失败'));
  }
});

module.exports = router;
