import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import '../../../../api/marianumcloud/talk/room/get_room_response.dart'; import '../../../../routing/app_routes.dart'; import '../../../../state/app/modules/chat_list/bloc/chat_list_bloc.dart'; import '../../../../widget/confirm_dialog.dart'; /// Opens an existing 1:1 chat with [actorId] or, after confirmation, creates /// one. Shared between the group-message context menu and the reactions /// overview (per-participant chat shortcut). void openOrCreateDirectChat( BuildContext context, { required String actorId, required String actorDisplayName, }) { final chatListBloc = context.read(); GetRoomResponseObject? findExisting() { final rooms = chatListBloc.state.data?.rooms; if (rooms == null) return null; for (final room in rooms.data) { if (room.type == GetRoomResponseObjectConversationType.oneToOne && room.name == actorId) { return room; } } return null; } void switchToChat(GetRoomResponseObject room) { // Pop the previous ChatView first — otherwise it stays in the // back-stack with a now-mismatched currentToken and renders empty // on back-swipe. Stop at popups so an open dialog stays alive. Navigator.of( context, ).popUntil((route) => route.isFirst || route is PopupRoute); AppRoutes.openChatByToken(context, room.token); } final existing = findExisting(); if (existing != null) { switchToChat(existing); return; } ConfirmDialog( title: 'Privatchat starten?', content: 'Es existiert noch kein Privatchat mit $actorDisplayName. ' 'Soll einer erstellt werden?', confirmButton: 'Erstellen', onConfirmAsync: () async { await chatListBloc.createDirectChat(actorId); final created = findExisting(); if (created == null) { throw Exception( 'Privatchat konnte nach dem Erstellen nicht gefunden werden.', ); } if (context.mounted) { switchToChat(created); } }, ).asDialog(context); }