-- =====================================================================================
-- Admin 商品模块 - 删除分类 RPC
-- 位置：docs/sql/30_rpc/product/
-- 对象类型：RPC 函数（SECURITY DEFINER）
-- 版本：v1（支持级联软删除商品关联）
-- 依赖：ml_categories, ml_products, ak_users 表已存在
-- =====================================================================================

CREATE OR REPLACE FUNCTION public.rpc_admin_category_delete(
    p_id UUID
)
RETURNS BOOLEAN
SECURITY DEFINER
SET search_path = public
LANGUAGE plpgsql
AS $$
DECLARE
    v_user_id UUID;
BEGIN
    -- 1. 权限检查
    IF NOT public.check_admin_permission('product:category:delete') THEN
        RAISE EXCEPTION 'Permission denied: product:category:delete';
    END IF;

    -- 2. 获取当前操作用户 ID
    SELECT id INTO v_user_id FROM public.ak_users WHERE auth_id = auth.uid();

    -- 3. 检查是否有子分类 (方案 1)
    IF EXISTS (
        SELECT 1 FROM public.ml_categories 
        WHERE parent_id = p_id AND deleted_at IS NULL
    ) THEN
        RAISE EXCEPTION '请先删除该分类下的子分类';
    END IF;

    -- 4. 级联软删除：该分类下的所有商品
    UPDATE public.ml_products
    SET deleted_at = now(),
        deleted_by = v_user_id
    WHERE category_id = p_id AND deleted_at IS NULL;

    -- 5. 执行软删除分类本身
    UPDATE public.ml_categories
    SET deleted_at = now(),
        deleted_by = v_user_id
    WHERE id = p_id AND deleted_at IS NULL;

    RETURN FOUND;
END;
$$;
