-- RPC: rpc_admin_delete_delivery_staff
-- 管理端删除配送员（支持权限检查）

CREATE OR REPLACE FUNCTION public.rpc_admin_delete_delivery_staff(
    p_id UUID
)
RETURNS BOOLEAN
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
    v_ok BOOLEAN;
    v_user_id UUID;
BEGIN
    -- 1. 权限检查 (使用通用权限校验函数)
    IF NOT public.check_admin_permission('delivery:staff:delete') THEN
        RAISE EXCEPTION 'Permission denied: delivery:staff:delete';
    END IF;

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

    -- 3. 执行软删除：标记 deleted_at
    UPDATE public.ml_delivery_staff
    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;
$$;

-- 授权
REVOKE ALL ON FUNCTION public.rpc_admin_delete_delivery_staff(UUID) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION public.rpc_admin_delete_delivery_staff(UUID) TO authenticated;
