-- RPC: rpc_admin_get_delivery_station_list
-- 管理端获取提货点/核销点分页列表
-- 支持按名称、地址或手机号搜索

CREATE OR REPLACE FUNCTION public.rpc_admin_get_delivery_station_list(
    p_search TEXT DEFAULT NULL,
    p_status SMALLINT DEFAULT NULL,
    p_page INTEGER DEFAULT 1,
    p_page_size INTEGER DEFAULT 20
)
RETURNS JSONB
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
    v_offset INTEGER := (p_page - 1) * p_page_size;
    v_total BIGINT;
    v_items JSONB;
BEGIN
    -- 1. 权限检查 (仅管理员)
    IF NOT EXISTS (
        SELECT 1 FROM public.ak_users 
        WHERE auth_id = auth.uid() AND role = 'admin'
    ) THEN
        RAISE EXCEPTION 'Permission denied';
    END IF;

    -- 2. 获取总数
    SELECT COUNT(*) INTO v_total
    FROM public.ml_delivery_stations
    WHERE (p_status IS NULL OR status = p_status)
      AND (p_search IS NULL OR p_search = '' 
           OR name ILIKE '%' || p_search || '%' 
           OR address ILIKE '%' || p_search || '%' 
           OR phone ILIKE '%' || p_search || '%');

    -- 3. 获取明细
    SELECT jsonb_agg(t) INTO v_items
    FROM (
        SELECT 
            id, name, phone, address, image, 
            lng, lat, status, sort_order, business_hours,
            created_at, updated_at
        FROM public.ml_delivery_stations
        WHERE (p_status IS NULL OR status = p_status)
          AND (p_search IS NULL OR p_search = '' 
               OR name ILIKE '%' || p_search || '%' 
               OR address ILIKE '%' || p_search || '%' 
               OR phone ILIKE '%' || p_search || '%')
        ORDER BY sort_order ASC, created_at DESC
        LIMIT p_page_size OFFSET v_offset
    ) t;

    -- 4. 返回结果
    RETURN jsonb_build_object(
        'total', v_total,
        'items', COALESCE(v_items, '[]'::jsonb)
    );
END;
$$;

-- 授权
REVOKE ALL ON FUNCTION public.rpc_admin_get_delivery_station_list(TEXT, SMALLINT, INTEGER, INTEGER) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION public.rpc_admin_get_delivery_station_list(TEXT, SMALLINT, INTEGER, INTEGER) TO authenticated;
