-- RPC: rpc_admin_delete_delivery_station
-- 管理端删除提货点/核销点（支持级联软删除配送员关联）

CREATE OR REPLACE FUNCTION public.rpc_admin_delete_delivery_station(
    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:station:delete') THEN
        RAISE EXCEPTION 'Permission denied: delivery:station:delete';
    END IF;

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

    -- 3. 级联软删除：该站点下的所有配送员
    UPDATE public.ml_delivery_staff
    SET deleted_at = now(),
        deleted_by = v_user_id
    WHERE station_id = p_id AND deleted_at IS NULL;

    -- 4. 执行软删除站点本身
    UPDATE public.ml_delivery_stations
    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_station(UUID) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION public.rpc_admin_delete_delivery_station(UUID) TO authenticated;
