-- RPC: rpc_admin_get_product_reviews
-- 作用：管理端分页获取商品评论列表，包含商品名称、用户名及规格
-- 位置：docs/sql/30_rpc/product/rpc_admin_get_product_reviews_v1.sql

CREATE OR REPLACE FUNCTION public.rpc_admin_get_product_reviews(
    p_search_product text DEFAULT NULL,
    p_search_user text DEFAULT NULL,
    p_status integer DEFAULT NULL,
    p_start_time timestamptz DEFAULT NULL,
    p_end_time timestamptz DEFAULT NULL,
    p_page integer DEFAULT 1,
    p_page_size integer DEFAULT 20
)
RETURNS TABLE (
    id uuid,
    product_id uuid,
    product_name text,
    product_image text,
    user_id uuid,
    username text,
    rating integer,
    content text,
    merchant_reply text,
    status integer,
    created_at timestamptz,
    total_count bigint
)
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
    v_offset integer := (p_page - 1) * p_page_size;
BEGIN
    -- 1. 权限检查
    IF NOT EXISTS (
        SELECT 1 FROM public.ak_users 
        WHERE ak_users.id = auth.uid() AND ak_users.role = 'admin'
    ) THEN
        RAISE EXCEPTION 'Permission denied';
    END IF;

    RETURN QUERY
    WITH filtered_reviews AS (
        SELECT 
            r.*,
            p.name as p_name,
            p.main_image_url as p_image,
            u.username as u_name,
            COUNT(*) OVER() as full_count
        FROM public.ml_product_reviews r
        LEFT JOIN public.ml_products p ON r.product_id = p.id
        LEFT JOIN public.ak_users u ON r.user_id = u.id
        WHERE (p_search_product IS NULL OR p.name ILIKE '%' || p_search_product || '%')
          AND (p_search_user IS NULL OR u.username ILIKE '%' || p_search_user || '%')
          AND (p_status IS NULL OR r.status = p_status)
          AND (p_start_time IS NULL OR r.created_at >= p_start_time)
          AND (p_end_time IS NULL OR r.created_at <= p_end_time)
    )
    SELECT 
        fr.id,
        fr.product_id,
        fr.p_name as product_name,
        fr.p_image as product_image,
        fr.user_id,
        fr.u_name as username,
        fr.rating,
        fr.content,
        fr.merchant_reply,
        fr.status,
        fr.created_at,
        fr.full_count as total_count
    FROM filtered_reviews fr
    ORDER BY fr.created_at DESC
    LIMIT p_page_size OFFSET v_offset;
END;
$$;

-- 授权
REVOKE ALL ON FUNCTION public.rpc_admin_get_product_reviews(text, text, integer, timestamptz, timestamptz, integer, integer) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION public.rpc_admin_get_product_reviews(text, text, integer, timestamptz, timestamptz, integer, integer) TO authenticated;
