import 'dart:async';
import 'package:bloc/bloc.dart';
import 'session_event.dart';
import 'session_state.dart';

class SessionBloc extends Bloc<SessionEvent, SessionState> {
  Timer? _expiryTimer;

  SessionBloc() : super(SessionInitial()) {
    on<SessionStarted>(_onSessionStarted);
    on<SessionExpired>(_onSessionExpired);
    on<SessionRefreshed>(_onSessionRefreshed);
    on<SessionEnded>(_onSessionEnded);
  }

  void _onSessionStarted(SessionStarted event, Emitter<SessionState> emit) {
    final expiresAt = DateTime.now().add(
      const Duration(minutes: 15),
    ); // Match Go
    emit(SessionActive(token: event.token, expiresAt: expiresAt));
    _startExpiryTimer(expiresAt);
  }

  void _onSessionExpired(SessionExpired event, Emitter<SessionState> emit) {
    _expiryTimer?.cancel();
    emit(SessionExpiredState());
  }

  void _onSessionRefreshed(SessionRefreshed event, Emitter<SessionState> emit) {
    final expiresAt = DateTime.now().add(const Duration(minutes: 15));
    emit(SessionActive(token: event.newToken, expiresAt: expiresAt));
    _startExpiryTimer(expiresAt);
  }

  void _onSessionEnded(SessionEnded event, Emitter<SessionState> emit) {
    _expiryTimer?.cancel();
    emit(SessionInitial());
  }

  void _startExpiryTimer(DateTime expiresAt) {
    _expiryTimer?.cancel();
    final duration = expiresAt.difference(DateTime.now());
    _expiryTimer = Timer(duration, () {
      add(SessionExpired());
    });
  }

  @override
  Future<void> close() {
    _expiryTimer?.cancel();
    return super.close();
  }
}
