/**
 * 主题管理（店铺装修可视化）— 三端（H5/PC/小程序）读取接口
 * 省胜优铺 · v1.4.3
 * 公开接口（无需登录）：返回某页可动态渲染的组件树 JSON
 *   GET /api/theme/page/:pageKey?theme_id=1&platform=h5|pc|miniapp
 * 缓存：进程内内存缓存（TTL 60s + active_theme_id 版本失效）
 *
 * 输出结构（前端据 type 动态渲染）：
 *   { theme: {id,name,style}, page: {page_key,is_public}, components: [{type,comp_key,status,config}] }
 */
const express = require('express');
const router = express.Router();
const { get, all } = require('../utils/db');
const { success, fail } = require('../utils/response');

const PAGE_KEYS = ['home', 'category', 'cart', 'user'];
const COMP_TYPES = [
  'banner', 'grid', 'goods-list', 'title', 'notice',
  'image', 'video', 'seckill', 'coupon', 'group-buy', 'bargain', 'article'
];

// ===== 内存缓存 =====
const cache = new Map(); // key -> { t, data }
const CACHE_TTL = 60 * 1000; // 60s
function cacheGet(key) {
  const e = cache.get(key);
  if (e && Date.now() - e.t < CACHE_TTL) return e.data;
  cache.delete(key);
  return null;
}
function cacheSet(key, data) { cache.set(key, { t: Date.now(), data }); }
function cacheClear() { cache.clear(); }

function safeJson(s) { try { return JSON.parse(s || '{}'); } catch (e) { return {}; } }
function readActiveThemeId() {
  const row = get("SELECT value FROM system_config WHERE key='active_theme_id'");
  return row ? Number(row.value) : 0;
}

router.get('/page/:pageKey', (req, res) => {
  const { pageKey } = req.params;
  if (!PAGE_KEYS.includes(pageKey)) return res.json(fail('无效页面', 404));
  const themeId = Number(req.query.theme_id) || readActiveThemeId() || 1;
  const platform = req.query.platform || 'h5';
  const ckey = `theme:page:${themeId}:${pageKey}:${platform}`;
  const cached = cacheGet(ckey);
  if (cached) return res.json(success(cached));

  const theme = get('SELECT * FROM store_theme WHERE id=?', [themeId]);
  if (!theme) return res.json(fail('主题不存在', 404));

  const page = get('SELECT * FROM store_theme_page WHERE theme_id=? AND page_key=?', [themeId, pageKey]);
  let components = [];
  let isPublic = 1;
  if (page && page.is_public) {
    isPublic = page.is_public;
    components = all('SELECT type, comp_key, status, config FROM store_theme_page_component WHERE page_id=? ORDER BY sort ASC, id ASC', [page.id])
      .filter((c) => COMP_TYPES.includes(c.type) && c.status === 1)
      .map((c) => ({ type: c.type, comp_key: c.comp_key, config: safeJson(c.config) }));
  }
  const data = {
    theme: { id: theme.id, name: theme.name, style: safeJson(theme.style || '{}') },
    page: { page_key: pageKey, is_public: isPublic },
    components
  };
  cacheSet(ckey, data);
  return res.json(success(data));
});

// 主题列表（三端拿到 style 用于应用配色）
router.get('/list', (req, res) => {
  const list = all('SELECT id, name, code, style FROM store_theme WHERE status=1 ORDER BY sort ASC, id ASC')
    .map((t) => ({ ...t, style: safeJson(t.style || '{}') }));
  return res.json(success(list));
});

module.exports = router;
module.exports._cacheClear = cacheClear;
