-- =====================================================================================
-- Admin 用户统计模块 - 性别比例 RPC（新增）
-- 说明: 基于 ak_users.gender 字段统计性别分布，兼容“未知”情况
-- 依赖: public.ak_users
-- =====================================================================================

-- 1) 检查 ak_users.gender 字段是否存在
SELECT 
  column_name, 
  data_type, 
  is_nullable, 
  column_default
FROM information_schema.columns
WHERE table_schema = 'public'
  AND table_name = 'ak_users'
  AND column_name = 'gender'
ORDER BY column_name;

-- 2) RPC: rpc_analytics_user_gender_distribution
-- 参数: p_start_date, p_end_date (可选，用于统计周期内新增/活跃用户的性别分布)
-- 返回: name, value (性别名称与人数)
CREATE OR REPLACE FUNCTION public.rpc_analytics_user_gender_distribution(
    p_start_date DATE DEFAULT NULL,
    p_end_date DATE DEFAULT NULL
)
RETURNS TABLE (
    name TEXT,
    value BIGINT
)
LANGUAGE plpgsql
AS $$
DECLARE
    has_gender BOOLEAN := FALSE;
    where_clause TEXT := '';
BEGIN
    -- 检查 gender 字段是否存在
    SELECT EXISTS (
        SELECT 1
        FROM information_schema.columns
        WHERE table_schema = 'public'
          AND table_name = 'ak_users'
          AND column_name = 'gender'
    ) INTO has_gender;

    IF NOT has_gender THEN
        -- 如果没有 gender 字段，返回全“未知”
        RETURN QUERY
        SELECT '未知'::TEXT AS name,
               COUNT(*)::BIGINT AS value
        FROM public.ak_users
        WHERE (p_start_date IS NULL OR p_end_date IS NULL) OR 
              (created_at::DATE BETWEEN COALESCE(p_start_date, '1970-01-01') AND COALESCE(p_end_date, CURRENT_DATE));
        RETURN;
    END IF;

    -- 构建时间过滤条件
    IF p_start_date IS NOT NULL AND p_end_date IS NOT NULL THEN
        where_clause := ' AND created_at::DATE BETWEEN ''' || p_start_date::TEXT || ''' AND ''' || p_end_date::TEXT || '''';
    END IF;

    -- 动态查询：按 gender 分组统计，兼容 NULL/空值
    RETURN QUERY EXECUTE '
        SELECT
            CASE 
                WHEN gender IS NULL OR gender = '''' OR LOWER(TRIM(gender)) IN (''null'', ''unknown'', ''未知'') THEN ''未知''
                WHEN LOWER(TRIM(gender)) IN (''male'', ''m'', ''男'', ''1'') THEN ''男''
                WHEN LOWER(TRIM(gender)) IN (''female'', ''f'', ''女'', ''2'') THEN ''女''
                ELSE ''其他''
            END AS name,
            COUNT(*)::BIGINT AS value
        FROM public.ak_users
        WHERE 1=1' || where_clause || '
        GROUP BY name
        ORDER BY value DESC
    ';
END;
$$;

-- 3) 快速验证：调用 RPC（全量用户）
SELECT * FROM public.rpc_analytics_user_gender_distribution();

-- 4) 验证：按月份调用（示例：2026-01）
SELECT * FROM public.rpc_analytics_user_gender_distribution(
    '2026-01-01',
    '2026-01-31'
);

-- 5) 数据完整性检查：查看当前 gender 字段的分布情况（用于调试）
SELECT 
    gender,
    COUNT(*) AS cnt,
    ROUND(COUNT(*) * 100.0 / NULLIF((SELECT COUNT(*) FROM public.ak_users), 0), 2) AS pct
FROM public.ak_users
GROUP BY gender
ORDER BY cnt DESC;