-- =====================================================================================
-- RPC: rpc_analytics_user_gender_distribution
-- Version: v1
-- Purpose: 统计指定周期内新增用户的性别分布（用于 Admin/Analytics 图表）
-- Security: SECURITY DEFINER + 固定 search_path + 入口角色鉴权
-- Depends: public.ak_users, public.get_current_user_role()
-- =====================================================================================

CREATE OR REPLACE FUNCTION public.rpc_analytics_user_gender_distribution(
  p_start_date DATE,
  p_end_date DATE
)
RETURNS TABLE (
  name TEXT,
  value BIGINT
)
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
BEGIN
  IF public.get_current_user_role() NOT IN ('admin', 'analytics') THEN
    RAISE EXCEPTION 'Permission denied: required role admin or analytics';
  END IF;

  RETURN QUERY
  SELECT
    CASE
      WHEN gender IS NULL OR TRIM(gender::text) = '' THEN '未知'
      WHEN LOWER(TRIM(gender::text)) = 'male' THEN '男'
      WHEN LOWER(TRIM(gender::text)) = 'female' THEN '女'
      WHEN LOWER(TRIM(gender::text)) = 'other' THEN '未知'
      ELSE '未知'
    END AS name,
    COUNT(*)::BIGINT AS value
  FROM public.ak_users
  WHERE created_at::DATE BETWEEN p_start_date AND p_end_date
  GROUP BY 1
  ORDER BY value DESC;
END;
$$;
