-- 入口模块地区管理 - 常用操作

-- 查看所有配置
SELECT id, name, jsonb_pretty(areas) AS configs FROM entry_modules;

-- 禁用某个入口在某个地区（示例：禁用id=1在"云浮"）
UPDATE entry_modules
SET areas = (
  SELECT jsonb_agg(CASE WHEN elem->>'area' = '云浮'
    THEN jsonb_set(elem, '{enabled}', 'false'::jsonb) ELSE elem END)
  FROM jsonb_array_elements(areas) AS elem
), updated_at = NOW()
WHERE id = 1;

-- 启用某个入口在某个地区（示例：启用id=1在"云浮"）
UPDATE entry_modules
SET areas = (
  SELECT jsonb_agg(CASE WHEN elem->>'area' = '云浮'
    THEN jsonb_set(elem, '{enabled}', 'true'::jsonb) ELSE elem END)
  FROM jsonb_array_elements(areas) AS elem
), updated_at = NOW()
WHERE id = 1;

-- 添加新地区（示例：为id=1添加"揭阳"）
UPDATE entry_modules
SET areas = areas || jsonb_build_array(
  jsonb_build_object('area', '揭阳', 'enabled', true, 'sort_order',
    (SELECT COALESCE(MAX((elem->>'sort_order')::int), 0) + 1
     FROM jsonb_array_elements(areas) AS elem))
), updated_at = NOW()
WHERE id = 1 AND NOT EXISTS (
  SELECT 1 FROM jsonb_array_elements(areas) AS elem WHERE elem->>'area' = '揭阳'
);

-- 删除某个地区配置（示例：从id=1删除"云浮"）
UPDATE entry_modules
SET areas = (SELECT jsonb_agg(elem) FROM jsonb_array_elements(areas) AS elem
  WHERE elem->>'area' != '云浮'
), updated_at = NOW()
WHERE id = 1;

-- 查看某个地区已启用的模块（示例：查看"梅州"）
SELECT id, name FROM entry_modules
WHERE areas @> '[{"area": "梅州", "enabled": true}]'::jsonb;

-- 统计每个地区的已启用模块数量
SELECT elem->>'area' AS area, COUNT(*) AS count
FROM entry_modules, jsonb_array_elements(areas) AS elem
WHERE (elem->>'enabled')::boolean = true
GROUP BY elem->>'area';
