/**
 * 页面装修可视化 — 公开读取接口（H5/PC/小程序）
 * 省胜优铺 · v1.4.3
 * GET /api/page-decor/layout/:pageKey  → 返回某页组件布局 JSON（动态渲染用）
 *   ?platform=h5|pc|miniapp
 * 内存缓存 60s；管理端保存后递增版本号即时失效（见 admin-page-decor 调 _clear）
 */
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();
const CACHE_TTL = 60 * 1000;
function cacheGet(k) { const e = cache.get(k); if (e && Date.now() - e.t < CACHE_TTL) return e.data; cache.delete(k); return null; }
function cacheSet(k, d) { cache.set(k, { t: Date.now(), data: d }); }
function cacheClear() { cache.clear(); }
function safeJson(s) { try { return JSON.parse(s || '{}'); } catch (e) { return {}; } }

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

  const layout = get('SELECT * FROM store_page_layout WHERE page_key=?', [pageKey]);
  let components = [];
  let isPublic = 1;
  if (layout && layout.is_public) {
    isPublic = layout.is_public;
    components = all('SELECT type, comp_key, status, config FROM store_page_component WHERE layout_id=? AND status=1 ORDER BY sort ASC, id ASC', [layout.id])
      .filter((c) => COMP_TYPES.includes(c.type))
      .map((c) => ({ type: c.type, comp_key: c.comp_key, config: safeJson(c.config) }));
  }
  const data = { page_key: pageKey, is_public: isPublic, components };
  cacheSet(ckey, data);
  return res.json(success(data));
});

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