-- =====================================================================================
-- Admin 商品管理 - 商品状态汇总统计 RPC
-- 位置：docs/sql/30_rpc/product/
-- 对象类型：RPC 函数（SECURITY DEFINER）
-- 版本：v1
-- 说明：统计出售中、仓库中、草稿箱、回收站各状态的商品数量
-- =====================================================================================

CREATE OR REPLACE FUNCTION public.rpc_admin_product_count_stats()
RETURNS JSONB
SECURITY DEFINER
SET search_path = public
LANGUAGE plpgsql
AS $$
DECLARE
    v_result 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;

    -- 2. 统计各状态数量
    -- status 定义：1:上架(出售中), 2:下架(仓库中), 3:草稿, 4:逻辑删除(回收站)
    SELECT jsonb_build_object(
        'selling', COUNT(*) FILTER (WHERE status = 1),
        'warehouse', COUNT(*) FILTER (WHERE status = 2),
        'draft', COUNT(*) FILTER (WHERE status = 3),
        'recycle', COUNT(*) FILTER (WHERE status = 4)
    ) INTO v_result
    FROM public.ml_products;

    RETURN v_result;
END;
$$;
