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

CREATE OR REPLACE FUNCTION public.rpc_admin_refund_order_list(
    p_page INTEGER DEFAULT 1,
    p_page_size INTEGER DEFAULT 15,
    p_refund_status INTEGER DEFAULT NULL,
    p_search 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_refund_orders ro
    WHERE (p_refund_status IS NULL OR ro.refund_status = p_refund_status)
      AND (p_search IS NULL OR (
          ro.refund_no ILIKE '%' || p_search || '%' OR
          EXISTS (
              SELECT 1 FROM public.ml_orders o 
              WHERE o.id = ro.order_id AND o.order_no ILIKE '%' || p_search || '%'
          )
      ));

    -- 3. 获取明细数据
    SELECT jsonb_agg(t) INTO v_items
    FROM (
        SELECT 
            ro.id,
            ro.refund_no,
            ro.refund_amount,
            ro.refund_status,
            ro.refund_reason,
            ro.applied_at,
            o.order_no,
            o.order_status,
            u.username as customer_name,
            u.phone as customer_phone,
            (
                SELECT jsonb_build_object(
                    'product_name', oi.product_name,
                    'image_url', oi.image_url
                )
                FROM public.ml_order_items oi
                WHERE oi.order_id = ro.order_id
                LIMIT 1
            ) as product_summary
        FROM public.ml_refund_orders ro
        LEFT JOIN public.ml_orders o ON ro.order_id = o.id
        LEFT JOIN public.ak_users u ON ro.user_id = u.id
        WHERE (p_refund_status IS NULL OR ro.refund_status = p_refund_status)
          AND (p_search IS NULL OR (
              ro.refund_no ILIKE '%' || p_search || '%' OR
              o.order_no ILIKE '%' || p_search || '%'
          ))
        ORDER BY ro.applied_at DESC
        LIMIT p_page_size
        OFFSET v_offset
    ) t;

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