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

CREATE OR REPLACE FUNCTION public.rpc_admin_order_list(
    p_page INTEGER DEFAULT 1,
    p_page_size INTEGER DEFAULT 15,
    p_order_status INTEGER DEFAULT NULL,
    p_search TEXT DEFAULT NULL,
    p_start_time TIMESTAMPTZ DEFAULT NULL,
    p_end_time TIMESTAMPTZ 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. 权限检查 (依赖 public.ak_users.role)
    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 (p_order_status IS NULL OR o.order_status = p_order_status)
      AND (p_start_time IS NULL OR o.created_at >= p_start_time)
      AND (p_end_time IS NULL OR o.created_at <= p_end_time)
      AND (
        p_search IS NULL 
        OR o.order_no ILIKE '%' || p_search || '%'
        OR u.username ILIKE '%' || p_search || '%'
        OR u.phone ILIKE '%' || p_search || '%'
      );

    -- 3. 获取明细列表
    SELECT jsonb_agg(t) INTO v_items
    FROM (
        SELECT 
            o.id,
            o.order_no,
            o.total_amount,
            o.paid_amount,
            o.discount_amount,
            o.order_status,
            o.payment_status,
            o.shipping_status,
            o.pay_type,
            o.channel_type,
            o.paid_at,
            o.created_at,
            u.username as buyer_name,
            u.phone as buyer_phone,
            (
                SELECT jsonb_build_object(
                    'product_name', oi.product_name,
                    'image_url', oi.image_url,
                    'quantity', oi.quantity
                )
                FROM public.ml_order_items oi
                WHERE oi.order_id = o.id
                ORDER BY oi.created_at ASC
                LIMIT 1
            ) as first_item_summary
        FROM public.ml_orders o
        LEFT JOIN public.ak_users u ON o.user_id = u.id
        WHERE (p_order_status IS NULL OR o.order_status = p_order_status)
          AND (p_start_time IS NULL OR o.created_at >= p_start_time)
          AND (p_end_time IS NULL OR o.created_at <= p_end_time)
          AND (
            p_search IS NULL 
            OR o.order_no ILIKE '%' || p_search || '%'
            OR u.username ILIKE '%' || p_search || '%'
            OR u.phone ILIKE '%' || p_search || '%'
          )
        ORDER BY 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;
$$;
