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

CREATE OR REPLACE FUNCTION public.rpc_admin_write_off_record_list(
    p_page INTEGER DEFAULT 1,
    p_page_size INTEGER DEFAULT 15,
    p_search TEXT DEFAULT NULL,
    p_verified_only BOOLEAN DEFAULT TRUE
)
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. 获取总数（核销订单类型 = 3）
    SELECT COUNT(*) INTO v_total
    FROM public.ml_orders o
    WHERE o.order_type = 3
      AND (p_verified_only = FALSE OR o.verified_at IS NOT NULL)
      AND (p_search IS NULL OR o.order_no ILIKE '%' || p_search || '%');

    -- 3. 获取明细
    SELECT jsonb_agg(t) INTO v_items
    FROM (
        SELECT 
            o.id,
            o.order_no,
            o.total_amount,
            o.payment_status,
            o.order_status,
            o.created_at,
            o.verified_at,
            buyer.username as customer_name,
            buyer.phone as customer_phone,
            verifier.username as verifier_name,
            (
                SELECT jsonb_build_object(
                    'product_name', oi.product_name,
                    'image_url', oi.image_url
                )
                FROM public.ml_order_items oi
                WHERE oi.order_id = o.id
                LIMIT 1
            ) as product_summary
        FROM public.ml_orders o
        LEFT JOIN public.ak_users buyer ON o.user_id = buyer.id
        LEFT JOIN public.ak_users verifier ON o.verifier_id = verifier.id
        WHERE o.order_type = 3
          AND (p_verified_only = FALSE OR o.verified_at IS NOT NULL)
          AND (p_search IS NULL OR o.order_no ILIKE '%' || p_search || '%')
        ORDER BY o.verified_at DESC NULLS LAST, o.created_at DESC
        LIMIT p_page_size
        OFFSET v_offset
    ) t;

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