restoreSession method

Future<bool> restoreSession()

Restore ALL sessions for this topic+mode, merging their messages chronologically. If an active session exists, new messages go there. Otherwise the conversation is read-only.

Implementation

Future<bool> restoreSession() async {
  if (params.topicId == null) return false;

  state = state.copyWith(isRestoring: true);

  try {
    final supabase = ref.read(supabaseDatasourceProvider);
    final sessionType = _modeToSessionType(params.mode);

    // Fetch every session (active + ended) for this topic+mode.
    final sessions = await supabase.getAllSessionsForTopic(
      topicId: params.topicId!,
      sessionType: sessionType,
    );

    if (sessions.isEmpty) {
      state = state.copyWith(isRestoring: false);
      return false;
    }

    // Identify the active session (for new messages) and latest ended
    // session (for card regeneration).
    final activeSession = sessions.where((s) => s.endedAt == null).lastOrNull;
    _sessionId = activeSession?.id;
    _sessionStartedAt = activeSession?.startedAt;

    final endedSessions = sessions.where((s) => s.endedAt != null);
    _endedSessionId = endedSessions.isEmpty ? null : endedSessions.last.id;

    // Load all messages across all sessions in chronological order.
    final sessionIds = sessions.map((s) => s.id).toList();
    final rawMessages = await supabase.getMessagesForSessions(sessionIds);

    final restored = rawMessages
        .map(
          (row) => ChatMessage(
            role: row['role'] as String,
            content: row['content'] as String,
            timestamp: DateTime.parse(row['created_at'] as String),
          ),
        )
        .toList();

    if (restored.isEmpty) {
      state = state.copyWith(isRestoring: false);
      return false;
    }

    state = state.copyWith(
      messages: restored,
      isRestoring: false,
      isReadOnly: activeSession == null,
    );
    return true;
  } catch (e) {
    debugPrint('Failed to restore session: $e');
    state = state.copyWith(isRestoring: false);
    return false;
  }
}