-- RPC: rpc_admin_get_division_list
-- 管理端获取事业部列表
-- 支持搜索事业部名称或负责人UID

CREATE OR REPLACE FUNCTION public.rpc_admin_get_division_list(
  p_search text DEFAULT NULL,
  p_page integer DEFAULT 1,
  p_page_size integer DEFAULT 20
)
RETURNS TABLE (
  uid uuid,
  name text,
  invite_code text,
  commission_ratio numeric,
  is_enabled boolean,
  end_time timestamptz,
  created_at timestamptz,
  "agentCount" bigint
)
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
  v_page integer := GREATEST(1, COALESCE(p_page, 1));
  v_page_size integer := LEAST(200, GREATEST(1, COALESCE(p_page_size, 20)));
  v_offset integer := (v_page - 1) * v_page_size;
BEGIN
  -- 仅管理员或分析员可调用
  IF NOT EXISTS (
    SELECT 1 FROM public.ak_users u
    WHERE u.id = auth.uid() AND u.role IN ('admin', 'analytics')
  ) THEN
    RAISE EXCEPTION 'permission denied';
  END IF;

  RETURN QUERY
  SELECT 
    d.uid,
    d.name,
    d.invite_code,
    d.commission_ratio,
    d.is_enabled,
    d.end_time,
    d.created_at,
    (SELECT COUNT(*) FROM public.ak_distribution_agents a WHERE a.division_uid = d.uid)::bigint AS "agentCount"
  FROM public.ak_distribution_divisions d
  WHERE (
    p_search IS NULL OR p_search = ''
    OR d.name ILIKE ('%' || p_search || '%')
    OR d.uid::text ILIKE ('%' || p_search || '%')
  )
  ORDER BY d.created_at DESC
  LIMIT v_page_size OFFSET v_offset;
END;
$$;

REVOKE ALL ON FUNCTION public.rpc_admin_get_division_list(text, integer, integer) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION public.rpc_admin_get_division_list(text, integer, integer) TO authenticated;
