-- RPC: rpc_admin_get_agent_list
-- 管理端获取代理商列表
-- 支持搜索代理商名称或负责人UID，并关联显示所属事业部信息

CREATE OR REPLACE FUNCTION public.rpc_admin_get_agent_list(
  p_search text DEFAULT NULL,
  p_page integer DEFAULT 1,
  p_page_size integer DEFAULT 20
)
RETURNS TABLE (
  uid uuid,
  name text,
  division_uid uuid,
  division_name text,
  commission_ratio numeric,
  is_enabled boolean,
  end_time timestamptz,
  created_at timestamptz,
  "staffCount" 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 
    a.uid,
    a.name,
    a.division_uid,
    d.name AS division_name,
    a.commission_ratio,
    a.is_enabled,
    a.end_time,
    a.created_at,
    (SELECT COUNT(*) FROM public.ak_promoter_relations r WHERE r.inviter_uid = a.uid)::bigint AS "staffCount"
  FROM public.ak_distribution_agents a
  JOIN public.ak_distribution_divisions d ON d.uid = a.division_uid
  WHERE (
    p_search IS NULL OR p_search = ''
    OR a.name ILIKE ('%' || p_search || '%')
    OR a.uid::text ILIKE ('%' || p_search || '%')
  )
  ORDER BY a.created_at DESC
  LIMIT v_page_size OFFSET v_offset;
END;
$$;

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