-- RPC: rpc_admin_get_agent_apply_list
-- 管理端获取代理商申请列表
-- 支持按状态过滤：all, pending, approved, rejected

CREATE OR REPLACE FUNCTION public.rpc_admin_get_agent_apply_list(
  p_status text DEFAULT 'all',
  p_search text DEFAULT NULL,
  p_page integer DEFAULT 1,
  p_page_size integer DEFAULT 20
)
RETURNS TABLE (
  id uuid,
  uid uuid,
  name text,
  phone text,
  dept_uid uuid,
  dept_name text,
  proof_images jsonb,
  status text,
  refusal_reason text,
  time timestamptz,
  invite_code text
)
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.id,
    a.uid,
    a.agent_name AS name,
    a.agent_phone AS phone,
    a.division_uid AS dept_uid,
    d.name AS dept_name,
    a.proof_images,
    a.status,
    a.refusal_reason,
    a.created_at AS time,
    d.invite_code
  FROM public.ak_distribution_agent_applications a
  JOIN public.ak_distribution_divisions d ON d.uid = a.division_uid
  WHERE (p_status = 'all' OR a.status = p_status)
    AND (
      p_search IS NULL OR p_search = ''
      OR a.agent_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_apply_list(text, text, integer, integer) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION public.rpc_admin_get_agent_apply_list(text, text, integer, integer) TO authenticated;
