-- =====================================================================================
-- Admin 订单功能 - 收银台订单列表分页查询 RPC
-- 位置：docs/sql/30_rpc/order/
-- 对象类型：RPC 函数（SECURITY DEFINER）
-- 版本：v1
-- =====================================================================================

CREATE OR REPLACE FUNCTION public.rpc_admin_cashier_order_list(
    p_page INTEGER DEFAULT 1,
    p_page_size INTEGER DEFAULT 15,
    p_search_order_no TEXT DEFAULT NULL,
    p_search_username TEXT DEFAULT NULL
)
RETURNS JSONB
SECURITY DEFINER
SET search_path = public
LANGUAGE plpgsql
AS $$
DECLARE
    v_offset INTEGER;
    v_total BIGINT;
    v_items JSONB;
BEGIN
    -- 1. 权限检查
    IF NOT EXISTS (
        SELECT 1 FROM public.ak_users 
        WHERE auth_id = auth.uid() AND role IN ('admin', 'analytics')
    ) THEN
        RAISE EXCEPTION 'Permission denied';
    END IF;

    v_offset := (p_page - 1) * p_page_size;

    -- 2. 总数：仅已支付订单
    SELECT COUNT(*) INTO v_total
    FROM public.ml_orders o
    LEFT JOIN public.ak_users u ON o.user_id = u.id
    WHERE o.paid_at IS NOT NULL
      AND (p_search_order_no IS NULL OR o.order_no ILIKE '%' || p_search_order_no || '%')
      AND (p_search_username IS NULL OR u.username ILIKE '%' || p_search_username || '%');

    -- 3. 明细
    SELECT jsonb_agg(t) INTO v_items
    FROM (
        SELECT 
            o.id,
            o.order_no,
            o.total_amount,
            o.discount_amount,
            o.paid_at,
            u.username as customer_name,
            u.phone as customer_phone
        FROM public.ml_orders o
        LEFT JOIN public.ak_users u ON o.user_id = u.id
        WHERE o.paid_at IS NOT NULL
          AND (p_search_order_no IS NULL OR o.order_no ILIKE '%' || p_search_order_no || '%')
          AND (p_search_username IS NULL OR u.username ILIKE '%' || p_search_username || '%')
        ORDER BY o.paid_at DESC
        LIMIT p_page_size
        OFFSET v_offset
    ) t;

    RETURN jsonb_build_object(
        'total', v_total,
        'items', COALESCE(v_items, '[]'::jsonb)
    );
END;
$$;