-- =====================================================================================
-- RPC: rpc_admin_kefu_word_category_delete
-- 位置：docs/sql/30_rpc/kefu/
-- 对象类型：RPC 函数 (SECURITY DEFINER)
-- 版本：v1
-- 说明：管理端删除话术分类（支持级联软删除话术）
-- =====================================================================================

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

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

    -- 3. 级联软删除：先标记该分类下的话术为删除
    UPDATE public.ml_kefu_words
    SET deleted_at = now(),
        deleted_by = v_user_id
    WHERE category_id = p_id AND deleted_at IS NULL;

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

    GET DIAGNOSTICS v_ok = ROW_COUNT;
    RETURN v_ok;
END;
$$;

COMMENT ON FUNCTION public.rpc_admin_kefu_word_category_delete IS '管理员删除话术分类';
